User Guide for Zustand
Introduction
Zustand is an extremely lightweight, fast, and easy-to-use state management library for React applications. Highlighted advantages of Zustand include:
- No need for a Provider to wrap the application
- Extremely concise syntax that reduces boilerplate code
- Excellent support for TypeScript
- High performance thanks to a mechanism that only re-renders necessary components.
Detail
First, install it into your project as follows:
Let's start with a simple Counter app example for you to easily understand how to use it.
Create file useCounterStore.ts
The code block above initializes a store to manage the count variable with a default value of 0, and defines 3 control functions: increment, decrement, and reset the value of count via Zustand's set function.
Create file page.tsx to use that store
This is the user interface using Ant Design to display the count value from the store and assign the increment, decrement, and reset functions to the corresponding buttons to update the state instantly on the UI.
The result will be as follows:
Next, I will guide you on using Zustand middleware in combination with some popular tools such as:
- devtools: supports debugging with Redux Devtools
- persist: saves data to localStorage
- immer: allows updating data in a mutable style for object data types; you don't need to return a new object as usual
Install immer additionally
Create file .env with the following content
Note that because I use it in a NextJS project, a NEXT_PUBLIC prefix is needed for frontend use; if you are using Vite, this is not necessary.
Create file useTodoStore.ts
This code block sets up a store for the Todo application.
- You can see that functions like addTodo and toggleTodo used with immer can directly modify the state object without needing to return a new object.
- The name: 'todo-storage' part is the key for saving to Local Storage.
- The enabled variable will take its value from the .env file defined above to only enable debug mode in development mode; when deploying to a production environment, it will be disabled.
Create file page.tsx to use useTodoStore
This is the main UI component of the Todo application, performing the connection of user actions (entering text, clicking the add button, checking completion, deleting) with the corresponding data processing functions in useTodoStore to manage the task list.
Checking the results will show that data has been saved in local storage, so you can reload the page and still keep the data.
When you change the state, it will be shown in the corresponding Redux Devtools.
Happy coding!
Comments
Post a Comment