Interview questions with answers
Zustand interview questions and answers
Stores, selectors, middleware, persistence and slices. Open any question to read its model answer; the multiple-choice set marks the right option and explains it.
- Subjective
- 30
- Objective
- 30
Subjective questions 30
1What is Zustand and why choose it?Asked almost every time
Zustand is a small, fast state-management library for React built on hooks. You create a store with create((set, get) => ({ ...state, ...actions })) and read it with the returned hook. There are no providers, reducers or boilerplate, components re-render only for the slices they select, and it works outside React too. It suits shared client state in apps that do not need Redux's structure.
2How do selectors prevent unnecessary re-renders?Asked almost every time
Calling useStore(state => state.count) subscribes the component only to count; it re-renders when that value changes by Object.is. Selecting the whole store re-renders on every change. For selecting several values as an object or array, use useShallow so a new object with equal fields does not trigger a render.
3How do you update state?Asked almost every time
Call set with a partial object or a function of the current state: set(state => ({ count: state.count + 1 })). Zustand shallow-merges the top level; nested objects must be copied (or use the Immer middleware). get() reads current state inside actions.
4How does Zustand work under the hood?Asked almost every time
create builds a store: a state object with setState, getState and subscribe. The React hook uses useSyncExternalStore to subscribe a component to the result of its selector, re-rendering only when that result changes (by Object.is).
5How do you handle async actions in Zustand?Asked almost every time
Actions are just functions, so make them async: set a loading flag, await the request, then set the result or error. No middleware is needed. For server data that needs caching and refetching, TanStack Query is usually a better fit.
6What state belongs in Zustand and what does not?Asked almost every time
Client state shared across components: UI preferences, auth session details, wizards, editor state, carts. Server data with caching needs is better in TanStack Query; form input state is better in a form library; URL-shareable state belongs in search params.
7What middleware does Zustand provide?Very often asked
persist saves state to storage (localStorage, sessionStorage, AsyncStorage) with versioning and migrations; devtools connects to Redux DevTools; immer allows mutable-style updates; subscribeWithSelector subscribes to slices outside React; combine infers types from initial state. Middlewares are composed by wrapping the creator.
8How do you organise a large store?Very often asked
Use the slices pattern: write separate slice creators (createBearSlice, createFishSlice) that each return part of the state and actions, and combine them in one create. Or use several independent stores for unrelated features. Keep actions in the store, next to the state they change.
9How do you use Zustand with Next.js and server rendering?Very often asked
A module-level store is shared across requests on the server, which can leak data between users. For per-request state, create the store inside a component with createStore (vanilla) and provide it through React context, reading with useStore(storeFromContext, selector). Keep server data in Server Components or TanStack Query.
10Zustand vs. Redux Toolkit vs. Context?Very often asked
Context is built in and fine for rarely changing values, but every consumer re-renders when the value changes. Zustand gives selective subscriptions with minimal code. Redux Toolkit adds strong conventions, middleware, DevTools time travel and RTK Query, which helps large teams. Server data belongs in a data-fetching library in all cases.
11How do you reset a Zustand store?Very often asked
Keep the initial state in a constant and add a reset: () => set(initialState) action. For tests, a common pattern resets all stores in afterEach by recording each store's initial state when created.
12How do you subscribe to changes outside React?Very often asked
Call useStore.subscribe(listener) to run code on every change, or use the subscribeWithSelector middleware to subscribe to a selected slice with an equality function and fireImmediately option. Unsubscribe with the returned function.
13How do you use immer middleware with Zustand?Very often asked
Wrap the creator with immer(...); then set(state => { state.todos.push(todo) }) can mutate a draft and Immer produces the immutable update. It simplifies deep nested updates.
14How do you combine multiple middleware?Very often asked
Nest them, typically devtools(persist(immer(creator), { name })), with devtools outermost so it records actions after other middleware. In TypeScript, use the curried create<State>()(...) form so types infer correctly.
15How do you use Zustand stores with React Context?Very often asked
For per-component or per-request stores, create a vanilla store with createStore in a provider (in a ref or useState), pass it through context, and read it with useStore(storeFromContext, selector). This is the recommended pattern for SSR in Next.js.
16How do you migrate persisted state between versions?Very often asked
Set version in persist options and provide a migrate(persistedState, version) function that transforms old shapes into the new one, so users' saved data keeps working after a release.
17How does the persist middleware handle hydration?Often asked
On load it reads storage and merges saved state into the store; in SSR the first render may show the default state, then the persisted one, causing hydration mismatches. Use onRehydrateStorage or persist.hasHydrated() to wait, render persisted UI only on the client, and use partialize to save only what is needed, with version and migrate for schema changes.
18How do you use a store outside components?Often asked
The hook returned by create also exposes getState(), setState() and subscribe(), so you can read or change state from event handlers, utilities or tests. createStore from zustand/vanilla makes a store with no React dependency.
19How do you test components using Zustand?Often asked
Reset the store between tests (save the initial state and call setState(initial, true) in afterEach), or mock the module as the docs show, then test behaviour through the UI. Pure store logic can be tested directly with getState().
20How do you type a store in TypeScript?Often asked
Declare the state and actions in an interface and call create<State>()((set) => ({ ... })); the extra parentheses (currying) let TypeScript infer middleware types correctly.
21How do you avoid stale closures with Zustand?Often asked
Read the latest state inside actions with get() instead of values captured from render, and in callbacks outside React use useStore.getState().
22How does Zustand compare with Jotai?Often asked
Zustand is a single store (or several) accessed with selectors, top-down. Jotai builds state from small atoms combined bottom-up, closer to React's model. Both are small and from the same open-source collective (pmndrs).
23How do you write transient updates that avoid re-renders?Often asked
Subscribe to the store in an effect and update a ref or the DOM directly in the listener, instead of selecting the value in render. This suits high-frequency values like mouse position or animation frames.
24How do you split a store across files?Often asked
Write slice creators (createBearSlice = (set, get) => ({...})), each in its own file, and combine them in create((...a) => ({ ...createBearSlice(...a), ...createFishSlice(...a) })), typing them with StateCreator.
25What does getInitialState provide?Often asked
Stores expose getInitialState(), returning the state the store was created with, useful for resets and for server rendering snapshots.
26How do you debug a Zustand store?Often asked
Use the devtools middleware with Redux DevTools to see actions and state over time, name actions in set(partial, false, 'todos/add'), and log changes with a simple subscribe.
27How do you derive computed values?Sometimes asked
Compute them in selectors (useStore(s => s.items.length)) or helper functions, rather than storing duplicates that can go out of sync. For expensive derivations, memoise the selector.
28Does Zustand need a Provider?Sometimes asked
No. Stores are module-level hooks by default. A provider and context are only needed when you want a separate store per component tree or per request.
29What is useShallow?Sometimes asked
A helper that wraps a selector returning an object or array and compares the result shallowly, so the component only re-renders when one of the selected values changes.
30Can Zustand be used outside React?Sometimes asked
Yes. zustand/vanilla's createStore creates a framework-independent store with get, set and subscribe, which other frameworks or plain JavaScript can use.
Objective questions 30
1Which function creates a Zustand store hook?Asked almost every time
Why: create returns a hook bound to the store.
2How do you subscribe a component to one value?Asked almost every time
Why: Selectors limit re-renders to that slice.
3Does Zustand require wrapping the app in a Provider?Asked almost every time
Why: Stores work without providers.
4Which React API does Zustand use for subscriptions?Asked almost every time
Why: Safe with concurrent rendering.
5How do you write an async action in Zustand?Asked almost every time
Why: Actions are plain functions.
6Which state fits TanStack Query better than Zustand?Asked almost every time
Why: Query handles caching and refetching.
7Which middleware saves state to localStorage?Very often asked
Why: persist writes to a storage engine.
8What does set do with a partial object?Very often asked
Why: Nested objects must be copied manually or with Immer.
9Which helper avoids re-renders when selecting an object of several values?Very often asked
Why: It compares the selected object shallowly.
10Which middleware connects to Redux DevTools?Very often asked
Why: devtools enables inspection and time travel.
11Which middleware allows subscribing to a selected slice?Very often asked
Why: With an equality function.
12Which typing form is recommended with middleware?Very often asked
Why: The curried form infers correctly.
13What is the recommended SSR pattern in Next.js?Very often asked
Why: Avoids sharing state between users.
14Which persist option upgrades old saved data?Very often asked
Why: Transforms old shapes.
15Which middleware order is typical?Very often asked
Why: Devtools outermost.
16How do you read state outside React?Often asked
Why: getState returns the current state.
17Why can a module-level store be risky with SSR?Often asked
Why: Server modules live across requests.
18Which option limits what persist saves?Often asked
Why: partialize selects the persisted slice.
19The slices pattern is used to…Often asked
Why: Each slice creator returns part of the store.
20How do you read the latest state inside an action?Often asked
Why: Avoids stale closures.
21Which library builds state from atoms?Often asked
Why: Bottom-up state.
22How do you update a value 60 times a second without re-rendering?Often asked
Why: Avoids render cost.
23Which type helps type slice creators?Often asked
Why: From zustand.
24What does the third argument in set(partial, false, 'name') do?Often asked
Why: With devtools middleware.
25Which function creates a store without React?Often asked
Why: Framework-independent.
26Which import creates a store without React?Sometimes asked
Why: Vanilla stores have no React dependency.
27Which middleware lets you write mutable-style updates?Sometimes asked
Why: Immer produces immutable updates from mutations.
28How large is Zustand roughly?Sometimes asked
Why: It is a tiny library.
29Who maintains Zustand?Sometimes asked
Why: Also Jotai and Valtio.
30How do you reset a store?Sometimes asked
Why: Keep initial state in a constant.
Track what you have practised and search every bank in your dashboard.
Start learning