In this article, we’ll explore how Zustand enables state replacement with the setState function, focusing on an interesting feature: overriding the state without merging. We'll explain how to use it with a simple test case.
Understanding State Merging vs State Overriding
Before looking at the code, it’s important to understand the difference between merging and overriding state.
Merging State: By default, when you update state in Zustand (or React), it merges the new state with the existing state. Only the updated fields are changed, while the rest of the state remains intact.
Overriding State: In contrast, overriding the state replaces the entire state with a new object, discarding any fields that were present in the previous state but are not part of the new state.
When to Override State
There are situations where replacing the entire state is necessary, for instance:
Resetting state after a form submission.
Replacing state entirely when loading a different dataset.
Test Case for Overriding Zustand State
Here’s a simple test case from Zustand’s codebase that demonstrates how to override the state using the setState function:
it('can set the store without merging', () => { const { setState, getState } = create( (_set) => ({ a: 1, }), ) // Should override the state instead of merging. setState({ b: 2 }, true) expect(getState()).toEqual({ b: 2 }) })
Breaking Down the Test
1. Creating the Store First, a Zustand store is created with an initial state:
const { setState, getState } = create( (_set) => ({ a: 1, }), )
The initial state is an object with a single property a set to 1. The create function returns two essential methods:
setState: This method is used to update the store’s state.
getState: This method retrieves the current state of the store.
2. Overriding the State The key operation here is to replace the current state, { a: 1 }, with a completely new state:
setState({ b: 2 }, true)
- By passing the true flag as the second argument, Zustand knows that it should override the state, rather than merge the new object { b: 2 } with the existing one. This completely replaces the previous state, so { a: 1 } is removed, and the new state becomes { b: 2 }.
3. Validating the State Replacement Finally, the test ensures that the state has been fully replaced:
expect(getState()).toEqual({ b: 2 })
The expectation is that after calling setState({ b: 2 }, true), the store’s state will only contain { b: 2 } and no longer contain { a: 1 }.
How Zustand Overrides State
The below image is from Zustand source code that sets state.
As you can see, if replace flag exists, nextState become the new state.
(replace ?? (typeof nextState !== 'object' || nextState === null))
This is a clever way, if replace is false, which it is by default, (typeof nextState !== ‘object’ || nextState === null)) condition is checked.
Conclusion
Zustand offers a straightforward way to manage state in React, and the ability to override the state completely using setState with the override flag provides additional flexibility. Whether you want to reset a form, load new data, or clear out old values, this feature allows you to fully control how state is managed and updated in your application.
About us:
At Think Throo, we are on a mission to teach the advanced codebase architectural concepts used in 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!)
Up skill your team with our advanced courses based on codebase architecture. Reach out to us at hello@thinkthroo.com to learn more!
References:
https://github.com/pmndrs/zustand/blob/v4.5.5/tests/basic.test.tsx#L471C13-L471C50
https://github.com/pmndrs/zustand/tree/v4.5.5?tab=readme-ov-file#overwriting-state
The above is the detailed content of How to override your Zustand state.. For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
