All quizzesHard
State Architecture
Preview — 3 of 10 questions
How do you build a concurrent-safe custom store?
javascript
function createStore(initialState) {
let state = initialState;
const listeners = new Set();
const getSnapshot = () => state;
const subscribe = (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
const setState = (update) => {
state = typeof update === "function" ? update(state) : update;
listeners.forEach(l => l()); // notify all subscribers
};
return { getSnapshot, subscribe, setState };
}
function useCustomStore(store, selector) {
return useSyncExternalStore(
store.subscribe,
() => selector(store.getSnapshot()),
);
}AuseSyncExternalStore is the React 18 API for external stores — it guarantees tearing-free reads in concurrent mode; all components see the same snapshot in a single render pass
BuseSyncExternalStore is unnecessary — useState + useEffect works the same way
CThis pattern leaks memory because listeners are never cleaned up
DCustom stores must extend React's Component class
How should you handle state that drives important UI transitions?
javascript
function SearchPage() {
const [query, setQuery] = useState("");
const [isPending, startTransition] = useTransition();
const handleSearch = (value) => {
setQuery(value); // urgent — input updates
startTransition(() => {
// Non-urgent — don't use startTransition for critical updates!
});
};
}AWrap all state updates in startTransition for better performance
BisPending should control whether the user can interact with the page
CstartTransition is equivalent to setTimeout(fn, 0) — same semantics
DOnly non-critical UI updates belong in transitions — urgent updates (user input, button clicks that need immediate feedback) must NOT use startTransition; transitions can be interrupted
How do you hydrate server-computed state to the client?
javascript
// Next.js — Server Component:
async function Page({ params }) {
const user = await getUserFromDB(params.id); // server-only
return <ClientProfile initialUser={user} />;
}
// Client Component:
"use client";
function ClientProfile({ initialUser }) {
const [user, setUser] = useState(initialUser); // hydrated from server
// mutations update local state
return <Profile user={user} onUpdate={setUser} />;
}APassing server data as initialUser prop initializes client state once — the client can then mutate it independently; this "hand-off" pattern avoids a client-side fetch for initial data
BServer-computed data can't be used to initialize client state
CThe server will re-compute and override user on every client interaction
DuseState(initialUser) re-fetches from the server on every render
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.