CodeBlanks Logo Icon CodeBlanks

What is Zustand?

Learn that Zustand is a simple state library.

What is Zustand?

Zustand is a small, fast state library. It does not need Redux's provider, action and reducer boilerplate; you write a store with a single create call.

A Zustand store is exported as a hook; components call this hook to read state. This cuts boilerplate significantly.

Zustand requires no provider; the store lives at module scope and is shared by every component.

Store with create

The create function takes a setup function; this function uses set and get parameters to define the state. The exported hook reads and changes this state.

Example: export const useCounter = create((set) => ({ count: 0, increment: () => set((s) => ({ count: s.count + 1 })) }));

In components you read only the count with const count = useCounter((s) => s.count); this prevents unnecessary renders.

Practice Write useCounter store

Complete the skeleton. Define useCounter store with create. State: { count: 0, increment: () => set((s) => ({ count: s.count + 1 })) }. Export with export const useCounter = create(...).

Starter code

App.jsx
import { create } from 'zustand';

// Write useCounter store here

Sample solution

App.jsx
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 NOT require?

App.jsx
The store lives at module scope.
  • Provider Correct answer
  • JavaScript
  • React
  • HTML

Explanation: Zustand does not require a provider.

2 create import

Question
import ____ from 'zustand';
Answer
import create from 'zustand';

Explanation: create is imported from zustand.

3 What is Zustand: match the terms

Term Meaning
create Builds store
set Updates state
get Reads state
useStore Returns hook

All lessons in Advanced