Zustand is a small, fast, and scalable state-management library for React, which serves as an alternative to more complex solutions like Redux. The main reason Zustand gained so much traction is its small size and simple syntax compared to Redux.
First, you need to install Zustand and TypeScript if you haven't already.
npm install zustand 'or' yarn add zustand
Zustand provides a create function to define your store. Let's walk through a basic example where we store and manipulate a count value.
Let’s create a file called store.ts where we have a custom hook useCounterStore():
import { create } from "zustand" type CounterStore = { count: number increment: () => void resetCount: () => void } export const useCounterStore = create((set) => ({ count: 0 increment: () => set((state) => ({ count: state.count 1 })), resetCount: () => set({ count: 0 }) }))
In this example:
count is a piece of state.
increaseCount and resetCount are actions that modify the state.
set is a function provided by Zustand to update the store.
import React from 'react' import { useCounterStore } from './store' const Counter: React.FC = () => { const count = useCounterStore((state) => state.count) // Get count from the store const increment = useCounterStore((state) => state.increment) // Get the action return () } export default Counter;{count}
Here, Counter is a React Component. As you can see, useCounterState() is used to access count and increment.
You can destructure the state instead of getting them directly like how it is in the following:
const {count, increment} = useCounterStore((state) => state)
But this approach makes it less performant. So, the best practice is to get access to the state directly like how it is shown before.
Making asynchronous action or calling API request to the server is also pretty simple in Zustand. Here, the following code explains it all:
export const useCounterStore = create((set) => ({ count: 0 increment: () => set((state) => ({ count: state.count 1 })), incrementAsync: async () => { await new Promise((resolve) => setTimeout(resolve, 1000)) set((state) => ({ count: state.count 1 })) }, resetCount: () => set({ count: 0 }) }))
Doesn’t it seem like a generic async function in JavaScript? First of all it runs the asynchronous code and then it sets the state with the given value.
Now, let’s see how you can use it on a react component:
const OtherComponent = ({ count }: { count: number }) => { const incrementAsync = useCounterStore((state) => state.incrementAsync) return ({count}) }
Until now, you've only accessed state inside React components. But what about accessing state from outside of React components? Yes, with Zustand you can access state from outside React Components.
const getCount = () => { const count = useCounterStore.getState().count console.log("count", count) } const OtherComponent = ({ count }: { count: number }) => { const incrementAsync = useCounterStore((state) => state.incrementAsync) const decrement = useCounterStore((state) => state.decrement) useEffect(() => { getCount() }, []) return ({count}) }
Here, you can see getCount() is accessing to state by getState()
We can set count as well:
const setCount = () => { useCounterStore.setState({ count: 10 }) }
The persist middleware in Zustand is used to persist and rehydrate the state across browser sessions, typically using localStorage or sessionStorage. This feature allows you to keep the state even after a page reload or when the user closes and reopens the browser. Here’s a detailed breakdown of how it works and how to use it.
Here’s how to set up a Zustand store with persist:
import create from 'zustand'; import { persist } from 'zustand/middleware'; // Define the state and actions interface BearState { bears: number; increase: () => void; reset: () => void; } // Create a store with persist middleware export const useStore = create( persist( (set) => ({ bears: 0, increase: () => set((state) => ({ bears: state.bears 1 })), reset: () => set({ bears: 0 }), }), { name: 'bear-storage', // Name of the key in localStorage } ) );
The state is saved under the key "bear-storage" in localStorage. Now, even if you refresh the page, the number of bears will persist across reloads.
By default, persist uses localStorage, but you can change it to sessionStorage or any other storage system. There are many things to cover on the topic of persisting state in Zustand. You will get a detailed tutorial/post on this topic, which will follow this post.
We all know how great is Redux as a state management tool. But Redux possess a kinda complex and large boilerplate. That is why more and more developers are choosing Zustand as their state management tool which is simple and scale-able.
But still you will see Redux is more recommended for seriously complex and nested state management.
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