Zustand
- React Native course
- Advanced
- Lesson 55/83
- 5 min
Learn lightweight state management with Zustand.
Zustand
Zustand is a lightweight state management framework. It needs much less boilerplate than Redux; no provider, action type or reducer is required. The store is defined in one file and components use it directly as a hook. Install with npm install zustand.
To create a store you call create. The returned value is a hook; components call it to read state. Zustand is very popular for small and medium React Native projects. Its uncomplicated API makes it fast to learn.
Defining the store
In Zustand the store is defined with a call to create. The function takes a callback that receives set and get parameters and returns an object. The returned object carries state fields and action functions.
Example: const useCounter = create((set) => ({ count: 0, increment: () => set((s) => ({ count: s.count + 1 })) })). Here count is the state, increment is the action. set is used to update state; get reads the current state. To export you simply add export.
Practice Write the useCounter store
Complete the empty file. Import create from zustand. Define export const useCounter with create((set) => ({ count: 0, increment: () => set((s) => ({ count: s.count + 1 })) })).
Starter code
import { create } from 'zustand';
// define the useCounter storeSample solution
import { create } from 'zustand';
export const useCounter = create((set) => ({
count: 0,
increment: () => set((s) => ({ count: s.count + 1 })),
}));Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Zustand reduce?
- The amount of boilerplate code Correct answer
- Animation quality
- Camera resolution
- The number of styles
Explanation: Zustand reduces the amount of boilerplate code.
2 The create call
export const useCounter = ____((set) => ({ count: 0, increment: () => set((s) => ({ count: s.count + 1 })) }));
export const useCounter = create((set) => ({ count: 0, increment: () => set((s) => ({ count: s.count + 1 })) }));
Explanation: create defines the store.
3 Match each part to its role
| Term | Meaning |
|---|---|
create |
Creates the store |
set |
Updates the state |
get |
Reads the state |
useCounter |
Used as a hook |