CodeBlanks Logo Icon CodeBlanks

Challenge: Zustand store

Write a cart store and connect it to two components.

Challenge: Zustand store

In this challenge you will write a state store with Zustand. The create function returns a hook; components call it and subscribe to the relevant slice.

A counter store holds count and increment. You update with set({ count: count + 1 }). A selector subscribes only to the needed slice.

Practice Write the Zustand store

Write a useCounter store. Import create. Define the store with create((set) => ({ count: 0, increment: () => set((s) => ({ count: s.count + 1 })) })) and export it.

Starter code

App.jsx
// Write the useCounter store here

Sample solution

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

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

Questions and answers

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

1 How do you update state in Zustand?

  • store.state = newState
  • With the set function Correct answer
  • With dispatch
  • With useState

Explanation: The set function updates state.

2 Fill in the blank: create a Zustand store

Question
import { create } from 'zustand';

const useCounter = ____((set) => ({ count: 0, increment: () => set((s) => ({ count: s.count + 1 })) }));
Answer
import { create } from 'zustand';

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

Explanation: create sets up a Zustand store.

All lessons in Advanced