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.

Quick reference: Key concepts and pitfalls on a couple of pages →
  1. 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 let variable 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. 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

    count is recreated as 0 on every render, and incrementing it doesn't ask React to re-render. You need const [count, setCount] = useState(0) and setCount(count + 1).

  3. 3. When should you use the functional update setCount(c => c + 1) instead of setCount(count + 1)?

    Correct answer: When the new value depends on the previous one

    count is a snapshot of the current render. Three setCount(count + 1) calls in one handler produce +1, while three setCount(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. 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.setState in classes, the useState setter replaces the value entirely - setForm({ email }) would lose name. Mutating and passing the same object is skipped, because React compares by reference (Object.is).

  5. 5. How do you remove an item with id from an array in state?

    Correct answer: setItems(items.filter(i => i.id !== id))

    State must be updated immutably: filter, map, spread and toSorted create a new array. splice and delete mutate the existing one, the reference stays the same, and React skips the update.

  6. 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 initializer useState(createInitialTodos) is called only on mount. It must be synchronous and pure.

  7. 7. Should you store fullName in state if you already have firstName and lastName?

    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. 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. 9. What does useReducer return?

    const [state, dispatch] = useReducer(reducer, initialState);

    Correct answer: The current state and a dispatch function to send actions

    You call dispatch({ type: 'added', text }), React calls reducer(state, action) and uses the returned value as the next state. dispatch is stable across renders, so it's safe to pass down and to use in effect dependencies.

  10. 10. What must a reducer function be like?

    Correct answer: Pure: (state, action) => newState with no side effects or mutations

    React 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. 11. When is useReducer usually a better choice than several useState calls?

    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 useState is simpler. useReducer doesn't make state global by itself.

  12. 12. What does a reducer usually return for an unknown action type?

    Correct answer: Throw an error, so the typo isn't missed

    Returning undefined would break the state. The React docs throw an error in default so typos in action types surface immediately; in TypeScript, a discriminated union of actions plus a never check catches them at compile time.

  13. 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. 14. What is prop drilling?

    Correct answer: Passing props through components that don't use them

    If App has a user that a deeply nested Avatar needs, every component in between must accept and forward user. It's verbose and couples the intermediate components to data they don't care about.

  15. 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. 16. Which technique often solves prop drilling without Context?

    Correct answer: Composition: pass elements via children

    <Layout sidebar={<UserMenu user={user} />}> - Layout doesn't need to know about user; it just renders the passed element. The React docs recommend trying composition first, since Context makes components harder to reuse.

  17. 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. 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/useReducer of the provider component.

  19. 19. What are the steps to use Context?

    Correct answer: createContext → wrap the tree in a provider with value → read with useContext

    const ThemeContext = createContext('light'); in React 19 you can render <ThemeContext value={theme}> directly (earlier versions used <ThemeContext.Provider>); any descendant calls useContext(ThemeContext).

  20. 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 hook useAuth() that throws a clear error if the provider is missing.

  21. 21. Which components re-render when a provider's value changes?

    Correct answer: Every component that reads this context with useContext

    All 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. 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. 23. Why wrap useContext in a custom hook like useAuth()?

    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 undefined somewhere deep in the code.

  24. 24. Can a component use several contexts at once?

    Correct answer: Yes: call useContext for each one

    const theme = useContext(ThemeContext); const user = useContext(UserContext); is normal. Splitting unrelated values into separate contexts also reduces unnecessary re-renders.

  25. 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. 26. What does createSlice generate?

    Correct answer: A reducer and action creators for each case reducer

    createSlice({ name: 'todos', initialState, reducers: { added(state, action) {...} } }) returns slice.reducer and slice.actions.added with the type 'todos/added'.

  27. 27. Why can you "mutate" state inside createSlice reducers?

    added(state, action) {
      state.items.push(action.payload);
    }

    Correct answer: Immer turns these changes into an immutable update under the hood

    state is an Immer draft: you write mutating code, and Immer produces a new object with structural sharing. Outside createSlice/createReducer mutations are still bugs.

  28. 28. What does configureStore do?

    Correct answer: Creates the store with combined reducers, thunk middleware and DevTools

    configureStore({ reducer: { todos: todosReducer } }) combines reducers, adds redux-thunk, enables Redux DevTools and, in development, checks for accidental mutations and non-serializable values.

  29. 29. How do you connect a Redux store to a React app?

    Correct answer: Wrap the app in <Provider store={store}> from react-redux

    Provider makes the store available to useSelector and useDispatch anywhere below. Under the hood it uses Context only to pass the store reference; subscriptions are handled separately and precisely.

  30. 30. What are useSelector and useDispatch for?

    Correct answer: Reading data from the store and getting the dispatch function

    const 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. 31. What is an action in Redux?

    Correct answer: A plain object with a type field

    { type: 'todos/added', payload: { id, text } }. Action creators from createSlice build such objects. Async logic (thunks) dispatches plain actions when data arrives.

  32. 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. createAsyncThunk dispatches pending/fulfilled/rejected around the request; for cached server data RTK Query is usually simpler.

  33. 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 calls useBear(...). No <Provider> is needed; the store lives in a module.

  34. 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 to user won't re-render it. Calling useStore() without a selector subscribes to the whole store and re-renders on any change.

  35. 35. How do you update state in Zustand?

    Correct answer: Call set inside an action

    set merges the returned object into the state at the top level (one level deep). Actions are usually defined right in the store, so components just call inc().

  36. 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. 37. How do you save a Zustand store to localStorage?

    Correct answer: Wrap the store creator in the persist middleware

    create(persist((set) => ({...}), { name: 'cart' })) saves and restores the state. You can choose the storage, persist only some fields (partialize) and migrate old versions.

  38. 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. 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. 40. What are the two required parts of useQuery?

    Correct answer: queryKey and queryFn

    useQuery({ queryKey: ['todo', id], queryFn: () => fetchTodo(id) }). The key identifies the cached data; everything the request depends on goes into it, so changing id loads different data.

  41. 41. What's needed before calling useQuery in an app?

    Correct answer: Create a QueryClient and wrap the app in QueryClientProvider

    The QueryClient holds the cache and defaults. Create it once (outside the component or in useState) so the cache isn't reset on every render. Redux isn't required.

  42. 42. How do you send a POST request (create an item) with TanStack Query?

    Correct answer: With useMutation and its mutate function

    Queries read data, mutations change it. const { mutate, isPending } = useMutation({ mutationFn: createTodo }). After success, related queries are usually invalidated so the list refetches.

  43. 43. Why does TanStack Query refetch data when you return to the browser tab?

    Correct answer: Data is stale by default and refetchOnWindowFocus is on

    The default is aggressive freshness: stale data is refetched on mount, window focus and reconnect. If the data rarely changes, raise staleTime globally or per query.

  44. 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. 45. What does createApi generate for an endpoint getPosts: builder.query(...)?

    Correct answer: A useGetPostsQuery hook, reducer and middleware

    The API slice's reducer and middleware are added to configureStore, and components call the generated hook: const { data, isLoading } = useGetPostsQuery().

  46. 46. How does an RTK Query mutation make lists refetch after adding an item?

    Correct answer: Queries declare providesTags, the mutation declares invalidatesTags

    getPosts provides the Post tag and addPost invalidates it - active queries with that tag refetch automatically. It's the RTK Query counterpart of invalidateQueries in TanStack Query.

  47. 47. What does the name SWR stand for?

    Correct answer: stale-while-revalidate

    The strategy comes from the HTTP Cache-Control extension: return stale data immediately for speed, revalidate in the background, then update the UI. Vercel's SWR library is built around it.

  48. 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. 49. What is a loader in 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. 50. What is an action in React Router?

    Correct answer: A function that handles a <Form> mutation

    <Form method="post"> calls the route's action with 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. 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. 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 useState calls.

  53. 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. 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. 55. What do the Redux DevTools let you do?

    Correct answer: Inspect actions and "time travel" between states

    configureStore enables the DevTools integration by default in development. Zustand can connect to the same extension via its devtools middleware.

  56. 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. createSelector adds memoization for derived data.

  57. 57. Where does the argument go when you dispatch todoAdded("Buy milk") created by createSlice?

    todoAdded(state, action) {
      state.push({ text: action.payload, done: false });
    }

    Correct answer: Into action.payload

    Generated action creators put their single argument into payload. A prepare callback can customize the payload, e.g. to add a generated id.

  58. 58. What does a Redux store object provide?

    Correct answer: getState(), dispatch() and subscribe()

    React-Redux hooks are built on these three methods. In tests or non-React code you can use them directly.

  59. 59. What is createAsyncThunk for?

    Correct answer: Wrapping a request with lifecycle actions

    Slices handle those actions in extraReducers to set loading flags and data. For cached server data, RTK Query usually needs less code.

  60. 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 get from the store creator

    set updates state and get reads the latest snapshot inside actions. Components should read state through selectors to subscribe to changes.

  61. 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 value changes. A store with selectors gives fine-grained subscriptions without splitting contexts.

  62. 62. Which fields of a useQuery result do you usually render from?

    const { data, error, isPending, isError } = useQuery({ queryKey: ["todos"], queryFn });

    Correct answer: isPending, isError and data

    status is 'pending' | 'error' | 'success'. Checking it first lets TypeScript narrow data to a defined value in the success branch.

  63. 63. How do you manually refetch a query, e.g. from a "Refresh" button?

    Correct answer: Call the refetch function returned by useQuery

    To refresh every component using the data, invalidating the key with queryClient.invalidateQueries is often more idiomatic.

  64. 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. 65. Which hooks does RTK Query generate for getPosts (query) and addPost (mutation) endpoints?

    Correct answer: useGetPostsQuery and useAddPostMutation

    Mutation hooks return a tuple: a trigger function and a result object ([addPost, { isLoading }] = useAddPostMutation()).

  66. 66. How does isLoading differ from isValidating in SWR?

    Correct answer: isValidating also covers background revalidation

    Show a skeleton for isLoading and at most a subtle indicator for isValidating, since cached data is still on screen.

  67. 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: fetch doesn't reject on 404 or 500 responses

    A thrown error is exposed as error and enables SWR's retry logic. You can attach status and the response body to the error for the UI.

  68. 68. How do you read the :id part of the URL /users/:id in 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 params in the argument.

  69. 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 the request) as an argument

    Loaders run outside components, so hooks aren't available. request.url gives access to search params too.

  70. 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. 71. A small app has a theme switch and a logged-in user. Which state tools are usually enough?

    Correct answer: useState/useReducer plus Context

    Start with built-in tools. Add a store when many components update shared state often, and a query library when server data needs caching.

  72. 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. 73. How can a component remember a setting in localStorage between 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 localStorage doesn't exist on the server, so read it after mount (or use useSyncExternalStore) to avoid hydration mismatches.

  74. 74. What does a typical action object for useReducer look like?

    dispatch({ type: "renamed", id: 3, title: "New title" });

    Correct answer: An object with a type string and any data

    Any shape works, but a type field is the convention. With TypeScript, a discriminated union of action types gives exhaustive checking in the reducer.

  75. 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.