The above code snippet is from vanilla.ts, when you set a state, Object.assign is used to update your state object.
Let’s first understand the basics of Object.assign:
The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
const target = { a: 1, b: 2 }; const source = { b: 4, c: 5 }; const returnedTarget = Object.assign(target, source); console.log(target); // Expected output: Object { a: 1, b: 4, c: 5 } console.log(returnedTarget === target); // Expected output: true
b value in the target object is replaced with b value in source object.
Really simple right? let’s now run some experiments and understand how Zustand’s setState leverages Object.assign() method.
// pulled from: https://github.com/pmndrs/zustand/blob/main/src/vanilla.ts#L76 state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
That’s nested ternary operator there in the above code snippet. if the replace is not null, state will be replace or if the nextState is not an object, just return nextState as is but what we are interested in is Object.assign({}, state, newState).
Let’s first log and see what is in state and nextState when you update your state. The example I picked is from demo example in Zustand’s source code. I modified the code a bit so we can put some console statements and run these experiments.
In this simple example, when the count is incremented, it comes down to updating the state object using Object.assign.
Next time, you are trying to perform some updates on your JSON object, use the Object.assign.
At Think Throo, we are on a mission to teach the best practices inspired by open-source projects.
10x your coding skills by practising advanced architectural concepts in Next.js/React, learn the best practices and build production-grade projects.
We are open source — https://github.com/thinkthroo/thinkthroo (Do give us a star!)
Looking to build bespoke web systems for your business? Contact us at [email protected]
Hey, I’m Ram. I am a passionate software engineer/OSS Tinkerer.
Checkout my website: https://www.ramunarasinga.com/
https://github.com/pmndrs/zustand/blob/main/src/vanilla.ts#L76
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3