Simplest state tutorial
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.
Understand Zustand Setup
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<CounterStore>((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.
Using the Store in a React Component
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 ( <div> <h1>{count}</h1> <button onClick={increment}>Increase Count</button> </div> ) } export default Counter;
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.
Asynchronous Actions
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<CounterStore>((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 ( <div> {count} <div> <button onClick={incrementAsync}>Increment</button> </div> </div> ) }
How to access the state outside React Component
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 ( <div> {count} <div> <button onClick={incrementAsync}>Increment</button> <button onClick={decrement}>Decrement</button> </div> </div> ) }
Here, you can see getCount() is accessing to state by getState()
We can set count as well:
const setCount = () => { useCounterStore.setState({ count: 10 }) }
Persist Middleware
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.
Basic Usage of persist
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<BearState>( 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.
Conclusion
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.
The above is the detailed content of Simplest state tutorial. For more information, please follow other related articles on the PHP Chinese website!

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.
