In this article, we will understand how .
, when you set a state, Object.assign is used to update your state object.
Let’s first understand the basics of Object.assign:
Object.assign()
The Object.assign() static method copies all 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.
Object.assign() in Zustand’s source code:
// 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
, we are on a mission to in Next.js/React, .
We are open source —
SOCIAL SHARE CARD GENERATOR