create
- React Native course
- Advanced
- Lesson 56/83
- 5 min
Learn to create stores with create.
A store with create
create is Zustand's single entry point. It takes a callback; the callback returns the state object. The state object contains both data fields and action functions. This distinction removes the need for a reducer/action split like in Redux.
The store returns a hook; this is why its name starts with the use prefix (useCart, useAuth). Components call this hook to select the field they want. The set function does a partial update; only the given fields change, the rest are kept.
Partial updates
set merges the object it receives into the current state. Calling set({ count: 5 }) only changes the count field; the rest of the state is kept. This behavior replaces the Object.assign or spread merge we do in Redux.
To update based on the previous state you write set((s) => ({ count: s.count + 1 })). Here s is the state before the update. This pattern is common for counters, list additions and form fields.
Practice Write the useCart store
Define the useCart store. Use create((set) => ({ items: [], addItem: (item) => set((s) => ({ items: [...s.items, item] })) })). Export it with export const.
Starter code
import { create } from 'zustand';
// define the useCart storeSample solution
import { create } from 'zustand';
export const useCart = create((set) => ({
items: [],
addItem: (item) => set((s) => ({ items: [...s.items, item] })),
}));Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the create parts
| Term | Meaning |
|---|---|
create |
Creates the store |
set |
Partial update |
get |
Reads state |
use... |
Hook name prefix |
2 The set call
increment: () => set((s) => ({ count: s.count + ____ })),
increment: () => set((s) => ({ count: s.count + 1 })),
Explanation: Write 1; this is the value used to grow the counter by one.
3 What kind of update does set do?
- A partial update
- Only reads Correct answer
- Deletes the entire state
- Sets up a provider
Explanation: set does a partial update.