CodeBlanks Logo Icon CodeBlanks

Store with create

Learn to write a store with create.

Using the hook

A Zustand store returns a hook; in components you call this hook with a selector. const count = useCounter((s) => s.count) reads only the count.

Using a selector triggers render only when the relevant piece changes. If the whole state changes, the component does not rerender; this boosts performance.

To read multiple values you can write const { count, increment } = useCounter(); but this triggers render on every change.

The set function

set is the store's state updater. It takes a function that returns a new object, or a direct object. set((s) => ({ count: s.count + 1 })) updates based on the previous state.

A Zustand set call automatically merges the new state; if you pass { count: 1 } the other fields are kept.

This behaviour mirrors the shallow merge of classic React setState; it feels familiar.

Practice Write useTheme store

Complete the skeleton. Define useTheme store with create. State: { theme: 'light', toggle: () => set((s) => ({ theme: s.theme === 'light' ? 'dark' : 'light' })) }. Export with export const useTheme = create(...).

Starter code

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

// Write useTheme store here

Sample solution

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

export const useTheme = create((set) => ({
  theme: 'light',
  toggle: () => set((s) => ({ theme: s.theme === 'light' ? 'dark' : 'light' })),
}));

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the benefit of a selector?

App.jsx
Relevant piece = selector.
  • It writes less code
  • It triggers render only when the relevant piece changes Correct answer
  • It compresses CSS
  • It deletes the store

Explanation: A selector prevents unnecessary renders.

2 set call

Question
increment: () => ____((s) => ({ count: s.count + 1 }));
Answer
increment: () => set((s) => ({ count: s.count + 1 }));

Explanation: set updates the state.

3 Store with create: match the terms

Term Meaning
selector Relevant piece
set Updates state
get Reads state
create Builds store

All lessons in Advanced