Middleware
- React Native course
- Advanced
- Lesson 59/83
- 5 min
Learn Zustand middleware (persist).
Middleware (persist)
The Zustand persist middleware makes state persistent; even if the app closes the value is kept. It is stored on the device with AsyncStorage and automatically restored on launch. It is ideal for user settings (theme, language), cart or login state.
Usage: persist((set) => ({...}), { name: 'storage-key' }). The name field is the AsyncStorage key. Persist wraps the store and writes to AsyncStorage on every state change. On launch it reads the saved value and initializes state.
A store with persist
When using persist the persist call is wrapped inside create. Example: create(persist((set) => ({ theme: 'light' }), { name: 'theme-storage' })). Here theme-storage is the key used in AsyncStorage.
In React Native a common AsyncStorage option is @react-native-async-storage/async-storage. Persist uses the browser localStorage by default; so in React Native you need to give a custom storage via the storage option. Without this setting persist does not work.
Practice A persistent theme store
Define the useTheme store. Import persist from zustand/middleware. Define with create(persist((set) => ({ theme: 'light' }), { name: 'theme-storage' })). Export it with export const.
Starter code
import { create } from 'zustand';
// define useTheme store with persistSample solution
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
export const useTheme = create(persist((set) => ({
theme: 'light',
}), { name: 'theme-storage' }));Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the persist parts
| Term | Meaning |
|---|---|
persist |
Middleware |
name |
AsyncStorage key |
AsyncStorage |
Device storage |
create |
Creates the store |
2 Write the storage key
persist((set) => ({ theme: 'light' }), { name: '____' })
persist((set) => ({ theme: 'light' }), { name: 'theme-storage' })
Explanation: theme-storage is the key name.
3 What does persist do?
- Makes state persistent Correct answer
- Changes styles
- Plays animations
- Opens the camera
Explanation: persist writes state to AsyncStorage and restores on launch.