State Management Junior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What is "state" in a React component?
Correct answer: Data whose change triggers a re-render
State is the component's memory between renders: a counter value, form input, whether a menu is open. A regular
letvariable resets on every render and its change doesn't tell React to update the UI. Props are read-only inputs owned by the parent.2. Why doesn't the counter on screen change?
function Counter() { let count = 0; return <button onClick={() => count++}>{count}</button>; }Correct answer: A local variable doesn't persist or trigger a render
countis recreated as0on every render, and incrementing it doesn't ask React to re-render. You needconst [count, setCount] = useState(0)andsetCount(count + 1).3. When should you use the functional update
setCount(c => c + 1)instead ofsetCount(count + 1)?Correct answer: When the new value depends on the previous one
countis a snapshot of the current render. ThreesetCount(count + 1)calls in one handler produce +1, while threesetCount(c => c + 1)produce +3, because each updater receives the result of the previous one. It also protects against stale closures in timers and effects.4. What's the right way to update one field of an object in state?
const [form, setForm] = useState({ name: "", email: "" });Correct answer:
setForm({ ...form, email: value })Unlike
this.setStatein classes, theuseStatesetter replaces the value entirely -setForm({ email })would losename. Mutating and passing the same object is skipped, because React compares by reference (Object.is).5. How do you remove an item with
idfrom an array in state?Correct answer:
setItems(items.filter(i => i.id !== id))State must be updated immutably:
filter,map, spread andtoSortedcreate a new array.spliceanddeletemutate the existing one, the reference stays the same, and React skips the update.6. Why pass a function to
useState(() => createInitialTodos())?Correct answer: So the expensive computation runs only on the first render
useState(createInitialTodos())calls the function on every render, even though the result is used only once. A lazy initializeruseState(createInitialTodos)is called only on mount. It must be synchronous and pure.7. Should you store
fullNamein state if you already havefirstNameandlastName?Correct answer: No - compute it during render
Redundant state leads to desynchronization and extra renders. Anything derivable from props and existing state is computed during render. If the computation is expensive, wrap it in
useMemo.8. What is "local" (component) state and when is it enough?
Correct answer: State used by one component or a small subtree
Most UI state is local: whether a dropdown is open, an input's text, the active tab. Keep state as close as possible to where it's used, and lift it up or move it into a store only when several distant components need it.
9. What does
useReducerreturn?const [state, dispatch] = useReducer(reducer, initialState);Correct answer: The current state and a
dispatchfunction to send actionsYou call
dispatch({ type: 'added', text }), React callsreducer(state, action)and uses the returned value as the next state.dispatchis stable across renders, so it's safe to pass down and to use in effect dependencies.10. What must a reducer function be like?
Correct answer: Pure:
(state, action) => newStatewith no side effects or mutationsReact may call the reducer more than once (e.g. in Strict Mode), so it must not make requests, set timers or mutate the state. Side effects belong in event handlers or effects.
11. When is
useReducerusually a better choice than severaluseStatecalls?Correct answer: When many related fields change in complex ways
A reducer collects all transitions in one place, so they're easy to read and test, and handlers only describe what happened. For a single toggle
useStateis simpler.useReducerdoesn't make state global by itself.12. What does a reducer usually return for an unknown action
type?Correct answer: Throw an error, so the typo isn't missed
Returning
undefinedwould break the state. The React docs throw an error indefaultso typos in action types surface immediately; in TypeScript, a discriminated union of actions plus anevercheck catches them at compile time.13. Why name actions after what happened (
'task_added') rather than what to do ('set_tasks')?Correct answer: The update logic then lives in the reducer
An action describes a user event ("a task was added"), and the reducer decides how state reacts.
set_*actions push the logic back into components and turn the reducer into a dumb setter. The same convention is used in Redux.14. What is prop drilling?
Correct answer: Passing props through components that don't use them
If
Apphas auserthat a deeply nestedAvatarneeds, every component in between must accept and forwarduser. It's verbose and couples the intermediate components to data they don't care about.15. What is "lifting state up"?
Correct answer: Moving state into the closest common parent
Two components that must stay in sync shouldn't each have their own copy. The parent owns the state and passes the value plus a callback down. This is the first tool to reach for, before Context or a store.
16. Which technique often solves prop drilling without Context?
Correct answer: Composition: pass elements via
children<Layout sidebar={<UserMenu user={user} />}>-Layoutdoesn't need to know aboutuser; it just renders the passed element. The React docs recommend trying composition first, since Context makes components harder to reuse.17. Is passing props down 2–3 levels a problem by itself?
Correct answer: Usually not: explicit props make data flow easy to trace
Explicit props are clear and easy to refactor. Prop drilling becomes a pain when data goes through many layers or many components need it - then composition, Context or a store make sense.
18. What problem does the Context API solve?
Correct answer: Passing a value deep into the tree
Context makes a value (theme, current user, locale) available to any descendant. It's a transport for values, not a state manager: the state itself still lives in
useState/useReducerof the provider component.19. What are the steps to use Context?
Correct answer:
createContext→ wrap the tree in a provider withvalue→ read withuseContextconst ThemeContext = createContext('light'); in React 19 you can render<ThemeContext value={theme}>directly (earlier versions used<ThemeContext.Provider>); any descendant callsuseContext(ThemeContext).20. What does
useContext(ThemeContext)return if there's no provider above?Correct answer: The default value from
createContext()The default is used when no provider is found up the tree. A common pattern is
createContext(null)plus a custom hookuseAuth()that throws a clear error if the provider is missing.21. Which components re-render when a provider's
valuechanges?Correct answer: Every component that reads this context with
useContextAll consumers of the context re-render, even if they use only one field of a large object. That's why Context is great for rarely changing values and less suitable for frequently changing state.
22. Which data is a good fit for Context?
Correct answer: Rarely changing values like theme or locale
Context shines for app-wide settings and dependencies (e.g. an API client). Rapidly changing values in a widely used context cause many re-renders; keep such state local or use a store with selectors.
23. Why wrap
useContextin a custom hook likeuseAuth()?export function useAuth() { const ctx = useContext(AuthContext); if (!ctx) throw new Error("useAuth must be used within AuthProvider"); return ctx; }Correct answer: To hide the context object and fail clearly when the provider is missing
Consumers import one hook instead of the context object, TypeScript gets a non-null type, and a missing provider produces a readable error instead of
undefinedsomewhere deep in the code.24. Can a component use several contexts at once?
Correct answer: Yes: call
useContextfor each oneconst theme = useContext(ThemeContext); const user = useContext(UserContext);is normal. Splitting unrelated values into separate contexts also reduces unnecessary re-renders.25. What is Redux Toolkit (RTK)?
Correct answer: The official, recommended way to write Redux code with less boilerplate
RTK bundles
configureStore,createSlice,createAsyncThunk, Immer and RTK Query. The Redux team recommends it for all new Redux code; hand-written action types and switch reducers are considered legacy.26. What does
createSlicegenerate?Correct answer: A reducer and action creators for each case reducer
createSlice({ name: 'todos', initialState, reducers: { added(state, action) {...} } })returnsslice.reducerandslice.actions.addedwith the type'todos/added'.27. Why can you "mutate"
stateinsidecreateSlicereducers?added(state, action) { state.items.push(action.payload); }Correct answer: Immer turns these changes into an immutable update under the hood
stateis an Immer draft: you write mutating code, and Immer produces a new object with structural sharing. OutsidecreateSlice/createReducermutations are still bugs.28. What does
configureStoredo?Correct answer: Creates the store with combined reducers, thunk middleware and DevTools
configureStore({ reducer: { todos: todosReducer } })combines reducers, addsredux-thunk, enables Redux DevTools and, in development, checks for accidental mutations and non-serializable values.29. How do you connect a Redux store to a React app?
Correct answer: Wrap the app in
<Provider store={store}>fromreact-reduxProvidermakes the store available touseSelectoranduseDispatchanywhere below. Under the hood it uses Context only to pass the store reference; subscriptions are handled separately and precisely.30. What are
useSelectoranduseDispatchfor?Correct answer: Reading data from the store and getting the
dispatchfunctionconst count = useSelector(state => state.counter.value)re-renders the component only when the selected value changes.const dispatch = useDispatch(); dispatch(increment())sends an action.31. What is an action in Redux?
Correct answer: A plain object with a
typefield{ type: 'todos/added', payload: { id, text } }. Action creators fromcreateSlicebuild such objects. Async logic (thunks) dispatches plain actions when data arrives.32. Where should a request to the server live in Redux Toolkit?
Correct answer: In a thunk or an RTK Query endpoint
Reducers must be pure.
createAsyncThunkdispatchespending/fulfilled/rejectedaround the request; for cached server data RTK Query is usually simpler.33. What is Zustand?
Correct answer: A small hook-based state manager
const useBear = create(set => ({ bears: 0, add: () => set(s => ({ bears: s.bears + 1 })) }))- and any component callsuseBear(...). No<Provider>is needed; the store lives in a module.34. How do you read just one field from a Zustand store?
const useStore = create((set) => ({ count: 0, user: null, inc: () => {} }));Correct answer:
const count = useStore((s) => s.count)A selector subscribes the component only to
count: changes touserwon't re-render it. CallinguseStore()without a selector subscribes to the whole store and re-renders on any change.35. How do you update state in Zustand?
Correct answer: Call
setinside an actionsetmerges the returned object into the state at the top level (one level deep). Actions are usually defined right in the store, so components just callinc().36. Does a Zustand store require a Provider component?
Correct answer: No: the store is a hook created at module level
That's one of Zustand's selling points. The flip side: a module-level store is shared by everything that imports it - on the server (SSR) you need a store per request, which the Next.js guide shows via Context.
37. How do you save a Zustand store to
localStorage?Correct answer: Wrap the store creator in the
persistmiddlewarecreate(persist((set) => ({...}), { name: 'cart' }))saves and restores the state. You can choose the storage, persist only some fields (partialize) and migrate old versions.38. How does server state differ from client (UI) state?
Correct answer: It lives on the server; the UI holds a cached copy
Server data (a list of orders) can change without the user's knowledge, so it needs caching, refetching and invalidation. UI state (whether a modal is open) belongs entirely to the client. Mixing them in one store leads to manual sync code.
39. What is TanStack Query (React Query) for?
Correct answer: Fetching and caching server data
It handles loading and error states, caching, deduplication, background refetching, retries, pagination and mutations - work that's tedious and error-prone with
useEffect+useState.40. What are the two required parts of
useQuery?Correct answer:
queryKeyandqueryFnuseQuery({ queryKey: ['todo', id], queryFn: () => fetchTodo(id) }). The key identifies the cached data; everything the request depends on goes into it, so changingidloads different data.41. What's needed before calling
useQueryin an app?Correct answer: Create a
QueryClientand wrap the app inQueryClientProviderThe
QueryClientholds the cache and defaults. Create it once (outside the component or inuseState) so the cache isn't reset on every render. Redux isn't required.42. How do you send a POST request (create an item) with TanStack Query?
Correct answer: With
useMutationand itsmutatefunctionQueries read data, mutations change it.
const { mutate, isPending } = useMutation({ mutationFn: createTodo }). After success, related queries are usually invalidated so the list refetches.43. Why does TanStack Query refetch data when you return to the browser tab?
Correct answer: Data is stale by default and
refetchOnWindowFocusis onThe default is aggressive freshness: stale data is refetched on mount, window focus and reconnect. If the data rarely changes, raise
staleTimeglobally or per query.44. What is RTK Query?
Correct answer: A data fetching and caching tool built into Redux Toolkit
You describe endpoints with
createApi, and it generates hooks (useGetPostsQuery) and manages caching, deduplication, refetching and invalidation - similar to TanStack Query but living in the Redux store.45. What does
createApigenerate for an endpointgetPosts: builder.query(...)?Correct answer: A
useGetPostsQueryhook, reducer and middlewareThe API slice's
reducerandmiddlewareare added toconfigureStore, and components call the generated hook:const { data, isLoading } = useGetPostsQuery().46. How does an RTK Query mutation make lists refetch after adding an item?
Correct answer: Queries declare
providesTags, the mutation declaresinvalidatesTagsgetPostsprovides thePosttag andaddPostinvalidates it - active queries with that tag refetch automatically. It's the RTK Query counterpart ofinvalidateQueriesin TanStack Query.47. What does the name SWR stand for?
Correct answer: stale-while-revalidate
The strategy comes from the HTTP
Cache-Controlextension: return stale data immediately for speed, revalidate in the background, then update the UI. Vercel's SWR library is built around it.48. What are the arguments of
useSWR(key, fetcher)?Correct answer: A unique key and a function that loads data
const { data, error, isLoading } = useSWR('/api/user', fetcher). The key identifies the cache entry: every component using the same key shares one request and one cached value.49. What is a
loaderin React Router?Correct answer: A function that loads a route's data before it renders
The router calls the loader on navigation and the component reads the result with
useLoaderData()(or via props in framework mode). Data loading starts with navigation instead of after render, which avoids request waterfalls.50. What is an
actionin React Router?Correct answer: A function that handles a
<Form>mutation<Form method="post">calls the route'sactionwith the form data. After the action, the router automatically revalidates the page's loaders, so the UI shows fresh data without manual cache updates.51. Does changing the argument of
useState(initial)on later renders update the state?function Price({ amount }) { const [value, setValue] = useState(amount); // amount changes from 10 to 20 - what is value? }Correct answer: No - it's used only on the first render
React keeps state between renders and ignores the argument afterwards. If the component should follow the prop, use the prop directly or reset with a
key.52. When should two pieces of state be combined into one object?
Correct answer: When they always change together
Grouping related values avoids forgetting to update one of them. Unrelated values are simpler as separate
useStatecalls.53. Where should a Context provider be placed?
Correct answer: As close as possible above its consumers
A lower provider limits which parts of the tree re-render when the value changes, and keeps unrelated features independent. Truly global values (theme, auth) can live near the root.
54. Which three principles describe classic Redux?
Correct answer: Single source of truth, read-only state, pure reducers
These rules make state changes predictable and traceable - the basis for devtools, time travel and easy testing.
55. What do the Redux DevTools let you do?
Correct answer: Inspect actions and "time travel" between states
configureStoreenables the DevTools integration by default in development. Zustand can connect to the same extension via itsdevtoolsmiddleware.56. Why define selector functions like
selectCartTotal(state)instead of inline lookups everywhere?Correct answer: Components don't depend on the state shape
When the state structure changes, only the selectors need updating.
createSelectoradds memoization for derived data.57. Where does the argument go when you dispatch
todoAdded("Buy milk")created bycreateSlice?todoAdded(state, action) { state.push({ text: action.payload, done: false }); }Correct answer: Into
action.payloadGenerated action creators put their single argument into
payload. Apreparecallback can customize the payload, e.g. to add a generated id.58. What does a Redux store object provide?
Correct answer:
getState(),dispatch()andsubscribe()React-Redux hooks are built on these three methods. In tests or non-React code you can use them directly.
59. What is
createAsyncThunkfor?Correct answer: Wrapping a request with lifecycle actions
Slices handle those actions in
extraReducersto set loading flags and data. For cached server data, RTK Query usually needs less code.60. How does a Zustand action read the current state?
const useCart = create((set, get) => ({ items: [], total: () => get().items.reduce((s, i) => s + i.price, 0), }));Correct answer: With
getfrom the store creatorsetupdates state andgetreads the latest snapshot inside actions. Components should read state through selectors to subscribe to changes.61. Why can Zustand cause fewer re-renders than a single Context for the same state?
Correct answer: Components subscribe to slices with selectors
Every consumer of a context re-renders when its
valuechanges. A store with selectors gives fine-grained subscriptions without splitting contexts.62. Which fields of a
useQueryresult do you usually render from?const { data, error, isPending, isError } = useQuery({ queryKey: ["todos"], queryFn });Correct answer:
isPending,isErroranddatastatusis'pending' | 'error' | 'success'. Checking it first lets TypeScript narrowdatato a defined value in the success branch.63. How do you manually refetch a query, e.g. from a "Refresh" button?
Correct answer: Call the
refetchfunction returned byuseQueryTo refresh every component using the data, invalidating the key with
queryClient.invalidateQueriesis often more idiomatic.64. What do the TanStack Query Devtools show?
Correct answer: All cached queries with their status and data
They are included only in development builds by default and are the fastest way to understand why something did or didn't refetch.
65. Which hooks does RTK Query generate for
getPosts(query) andaddPost(mutation) endpoints?Correct answer:
useGetPostsQueryanduseAddPostMutationMutation hooks return a tuple: a trigger function and a result object (
[addPost, { isLoading }] = useAddPostMutation()).66. How does
isLoadingdiffer fromisValidatingin SWR?Correct answer:
isValidatingalso covers background revalidationShow a skeleton for
isLoadingand at most a subtle indicator forisValidating, since cached data is still on screen.67. Why should an SWR fetcher throw on non-OK HTTP responses?
const fetcher = async (url) => { const res = await fetch(url); if (!res.ok) throw new Error("Request failed"); return res.json(); };Correct answer:
fetchdoesn't reject on 404 or 500 responsesA thrown error is exposed as
errorand enables SWR's retry logic. You can attachstatusand the response body to the error for the UI.68. How do you read the
:idpart of the URL/users/:idin a React Router component?Correct answer:
const { id } = useParams()Params are always strings, so convert them if you need numbers. In loaders they arrive as
paramsin the argument.69. How does a React Router loader know which item to load?
export async function loader({ params }) { return getUser(params.id); }Correct answer: It receives
params(and therequest) as an argumentLoaders run outside components, so hooks aren't available.
request.urlgives access to search params too.70. Where should a search box's query live so the page can be shared and survives reload?
const [searchParams, setSearchParams] = useSearchParams(); const q = searchParams.get("q") ?? "";Correct answer: In the URL search params
The URL is state that users can bookmark and share, and Back/Forward works naturally. Loaders and query keys can derive from it.
71. A small app has a theme switch and a logged-in user. Which state tools are usually enough?
Correct answer:
useState/useReducerplus ContextStart with built-in tools. Add a store when many components update shared state often, and a query library when server data needs caching.
72. What is a "store" in state management libraries?
Correct answer: An object holding shared state outside components
Redux, Zustand and MobX stores live outside the React tree, so any component can read or update them without passing props.
73. How can a component remember a setting in
localStoragebetween visits?const [theme, setTheme] = useState(() => localStorage.getItem("theme") ?? "light"); useEffect(() => localStorage.setItem("theme", theme), [theme]);Correct answer: Read in a lazy initializer, write in an effect
In SSR apps
localStoragedoesn't exist on the server, so read it after mount (or useuseSyncExternalStore) to avoid hydration mismatches.74. What does a typical action object for
useReducerlook like?dispatch({ type: "renamed", id: 3, title: "New title" });Correct answer: An object with a
typestring and any dataAny shape works, but a
typefield is the convention. With TypeScript, a discriminated union of action types gives exhaustive checking in the reducer.75. What is the "atomic" state approach of libraries like Jotai?
Correct answer: State is split into small independent atoms
Derived atoms combine others, similar to computed values. It suits apps with many small interdependent pieces of state.