Deep runtime internals, memory models, distributed design, concurrency failure modes, and architectural decisions.
Answer: Zustand is built on a vanilla JavaScript state engine that handles reactive bindings independently from React's rendering pipeline.
At its core, a Zustand store is a simple JS object closure that contains:
Set of callback listener functions.When you call set(nextState):
Object.is).subscribers Set and executes every callback function synchronously.Historically (Zustand v3 and below), Zustand used standard useEffect subscriptions and custom React forcing-update hacks to trigger component paint cycles.
However, with the introduction of React 18's Concurrent Rendering, this created a high risk of tearing—where a fast external store update occurs mid-render, causing half of the page to render with the old state and half with the new state.
To solve this, modern Zustand (v4 and v5) uses useSyncExternalStore (uSES) under the hood:
useStore(selector), uSES subscribes that component's react fiber node to the Zustand store's vanilla subscribe function.getSnapshot) to read the state.Answer: In a standard client-only Single Page Application (SPA), a Zustand store is instantiated once in the browser (a Singleton), which is perfectly safe because each user has their own isolated browser environment.
When rendering on the server in Next.js (SSR or Route Handlers):
set({ cart: userACart })), that state is written to the singleton store.To prevent state pollution, you must ensure that every single request gets its own newly instantiated Zustand store. This is achieved by:
value prop.Answer: Zustand requires all state updates to be immutable. If you have deeply nested state:
// Example Nested State
const state = {
user: {
profile: {
address: { city: 'Kolkata' }
}
}
};
To modify city using raw JS, you must manually spread every level of the object hierarchy to preserve references:
set((state) => ({
user: {
...state.user,
profile: {
...state.user.profile,
address: {
...state.user.profile.address,
city: 'Mumbai'
}
}
}
}));
... will wipe out sibling state variables).The immer middleware wraps the state mutator function in a proxy using the Immer library. It allows you to write standard, direct mutating code (e.g., state.user.profile.address.city = 'Mumbai') on a temporary "draft" state, and automatically translates it into highly optimized immutable updates.
import { immer } from 'zustand/middleware/immer';
const useStore = create(
immer((set) => ({
user: { profile: { address: { city: 'Kolkata' } } },
updateCity: (newCity) => set((state) => {
state.user.profile.address.city = newCity; // Mutate directly on the draft!
})
}))
);
Answer:
A custom middleware is a function that takes a store creator function f and returns a modified store creator function. This modified creator intercept parameters like set and get before executing the actual store.
const myCustomMiddleware = (config) => (set, get, api) => {
// 1. Intercept 'set' and add custom behaviors
const modifiedSet = (nextStateOrFn, replace) => {
console.log("State is about to change!");
set(nextStateOrFn, replace); // Execute actual state change
console.log("State change complete:", get());
};
// 2. Inject modified set into the original config creator
return config(modifiedSet, get, api);
};
This clean abstraction is what enables developers to inject logging, analytic tags, telemetry metrics, or custom state locks into any Zustand store without modifying any actual business logic components.
Answer: Sometimes, you need to react to high-frequency state updates (e.g., mouse positions, scrolling offsets, physics coordinate matrices, audio wave frequencies, or rendering on WebGL/Canvas).
If you bind these properties to standard React component state, React will trigger 60 to 120 re-renders per second, locking the browser's main thread and causing severe visual performance degradation.
Zustand allows you to subscribe to store updates without binding them to React components (bypassing React rendering entirely). You do this by calling store.subscribe and directly modifying DOM node references or Canvas contexts inside the subscriber callback.
// 1. Store tracking mouse positions
const useCoordStore = create(() => ({ x: 0, y: 0 }));
// 2. High-performance DOM Updater component
export function CursorPointer() {
const elementRef = useRef(null);
useEffect(() => {
// Subscribe directly to the store changes
// This callback runs outside of React's fiber loop and never triggers a re-render!
const unsubscribe = useCoordStore.subscribe(
(state) => {
if (elementRef.current) {
// Mutate DOM properties directly for fluid 120fps layout shifts
elementRef.current.style.transform = `translate3d(${state.x}px, ${state.y}px, 0)`;
}
}
);
return unsubscribe; // Unsubscribe on unmount
}, []);
// Notice we do NOT pass state values to the returned JSX
return <div ref={elementRef} className="cursor-dot" style={{ position: 'absolute' }} />;
}
This guarantees optimal performance by letting the browser's DOM compositor handle layout transforms directly, skipping React's reconciliation diffing entirely.
You've completed the 5 free sample questions. Get unrestricted lifetime access to every question, model answer, implementation challenge, and all 27+ technologies for a single payment.
₹399 India / $9 International · One-time settlement · Zero subscription