Blog
Object.assign() usage in Zustand source code.

Object.assign() usage in Zustand source code.

In this article, we will understand how Object.assign() is used in Zustand’s source code.

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:

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.

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 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.

About us:

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 hello@thinkthroo.com

References:

  1. https://github.com/pmndrs/zustand/blob/main/src/vanilla.ts#L76

  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign