Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 77 ยท Web and Frontend Interview Questions

React: Redux, Redux Toolkit, Thunks and Context

Answer Redux interview questions: store, reducers, middleware, thunks, selectors, Redux Toolkit and when Context is enough, with runnable stand-ins.

"Do you know Redux?" is still a common question, even in teams that no longer use it everywhere. Interviewers use it to check whether you understand state management as an idea: one source of truth, updates as plain data, and pure functions that compute the next state. If you can explain those three things, the library API is just detail.

The real Redux packages cannot be installed in the in-page runner (no npm packages are available), so the React and Redux Toolkit code below is read-only. Next to it you get stand-ins in plain JavaScript that are small enough to read in a minute and behave like the real thing for the cases shown. They are models, not the library's source. For the React basics see React Interview Questions and the React tutorial.

The Redux loop

Dispatch The UI sends an action.
Reduce A pure function returns the next state.
Store One object holds the state.
Notify Subscribers read the new state.

State changes only by dispatching an action.

1 / 2

What is Redux, and what are its three principles?

Short answer: Redux is a predictable container for application state. The whole state lives in one store. You change it only by dispatching an action, a plain object such as { type: "cart/added", payload: 7 }. A reducer is a pure function (state, action) => newState that decides what the new state is.

The three principles interviewers expect: a single source of truth, state is read-only (you never mutate it, you dispatch), and changes are made with pure functions. "Pure" means the same input always gives the same output and nothing outside the function is touched: no fetch, no Math.random(), no Date.now(), no mutation of the old state.

Why bother? Because every change is a named event, so you can log them, replay them, undo them and test the reducer with plain function calls. That is what the Redux DevTools "time travel" uses.

Here is a stand-in for the core of Redux. The real createStore is a little longer (it handles errors, unsubscribe edge cases and replacing reducers) but the idea is exactly this.

JS Stand-in: createStore in about fifteen lines

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line is a point worth saying out loud: when a reducer returns the same reference, subscribers can use a cheap === check to know nothing changed. That is why you return state unchanged in default and never mutate and return the same object after a change.

What is middleware, and what is a thunk?

Q: Where do side effects such as API calls go, if reducers must be pure? Not in the reducer. Put them in middleware, which sits between dispatch and the reducer. Middleware can log, delay, cancel or transform actions, and it can let you dispatch things other than plain objects.

Redux Thunk is the most common middleware. A thunk is a function that is dispatched instead of an object. The middleware sees that it is a function and calls it with dispatch and getState, so the function can do async work and dispatch ordinary actions when the result arrives. The usual three-action pattern is "request started", "succeeded" and "failed".

JavaScript
// Real Redux Thunk usage (read-only: needs the redux-thunk package)
const loadUser = (id) => async (dispatch, getState) => {
  dispatch({ type: "user/loading" });
  try {
    const res = await fetch(`/api/users/${id}`);
    dispatch({ type: "user/loaded", payload: await res.json() });
  } catch (error) {
    dispatch({ type: "user/failed", error: String(error) });
  }
};
// store.dispatch(loadUser(7));

The next TryIt builds the middleware chain and the thunk middleware itself. The real thunk is a three-line function; ours is the same.

JS Stand-in: applyMiddleware and a thunk

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the log: the thunk middleware comes first and swallows the function, so the logger never sees [thunk]. Each plain action the thunk dispatches goes through the full chain again and does reach the logger. Middleware order matters: put logger first and it would print [thunk] too.

How do components read the store? Selectors and connect

Q: What does useSelector (or the older mapStateToProps) do? It reads a slice of the store for a component and re-renders that component when the selected value changes. React-Redux compares the previous and next selected values with ===. If your selector returns a new object or array every time, the component re-renders on every store update, even when nothing relevant changed.

JSX
// Read-only: needs react-redux
function CartBadge() {
  const count = useSelector((state) => state.cart.items.length); // a number: cheap to compare
  return <span>{count}</span>;
}

// Bad: creates a new array each call, so === is always false
const expensive = useSelector((state) => state.cart.items.filter((i) => i.price > 100));

The fixes are to select primitives, to select the stored reference directly, or to memoize derived data with a selector library such as Reselect (createSelector), which recomputes only when its inputs change by reference.

Before hooks, React-Redux used connect(mapStateToProps, mapDispatchToProps)(Component), a higher-order component that did the same work and passed the results as props. mapStateToProps is the "select" half, mapDispatchToProps binds action creators to dispatch. Hooks (useSelector, useDispatch) replaced it in new code, but old code bases are full of connect, so you should recognize it.

JS Stand-in: why a new array from a selector causes extra renders

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Short answer: Redux Toolkit (RTK) is the official, opinionated toolset for writing Redux. It removes the boilerplate that made classic Redux unpopular: hand-written action types, switch statements, spread-everywhere immutable updates and store setup.

The pieces to name: configureStore (sets up the store with thunk and DevTools by default), createSlice (generates action creators and a reducer from one object), createAsyncThunk (wraps the pending/fulfilled/rejected pattern), and RTK Query (data fetching and caching, which removes many hand-written thunks).

Inside createSlice you may write code that looks like mutation. That is safe because RTK uses Immer: you receive a draft, Immer records your changes and produces a new immutable state. It only works inside the slice reducers and createReducer, not in arbitrary code.

JSX
// Read-only: needs @reduxjs/toolkit and react-redux
import { configureStore, createSlice } from "@reduxjs/toolkit";

const cartSlice = createSlice({
  name: "cart",
  initialState: { items: [] },
  reducers: {
    added(state, action) {
      state.items.push(action.payload);   // looks like mutation; Immer makes it immutable
    },
    cleared(state) {
      state.items = [];
    },
  },
});

export const { added, cleared } = cartSlice.actions;   // action creators: added(7) -> { type: "cart/added", payload: 7 }
export const store = configureStore({ reducer: { cart: cartSlice.reducer } });

A frequent follow-up is "what does Immer do?" The stand-in below copies the idea with a tiny draft that records which keys you touched. Real Immer uses a proxy, tracks nested changes and freezes results; this model only handles one level.

JS Stand-in: write 'mutating' code, get a new object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Redux or Context: which should you choose?

This is the question that separates memorized answers from understanding. Context is not a state management tool; it is a way to pass a value down the tree without prop drilling. You still need useState or useReducer to hold the state.

The real difference is how updates reach components. When a Context value changes, every component that calls useContext for it re-renders, and you cannot select a slice. React-Redux lets each component subscribe to just the part it reads. So Context works well for values that change rarely (theme, locale, current user), and Redux (or Zustand, Jotai, RTK Query) pays off when many components read different parts of fast-changing shared state.

Question Context + useReducer Redux Toolkit
Boilerplate Little More setup, less than classic Redux
Reading a slice Whole value; all consumers re-render Per-component selectors
Middleware, DevTools You build it Built in
Async data Hand-written createAsyncThunk, RTK Query
Best for Theme, auth user, locale Large shared state, complex updates

A good closing line in an interview: "I start with local state, lift it when needed, use Context for low-frequency globals, and reach for Redux Toolkit or a server-state library when state is shared widely and updated often."

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must a Redux reducer be pure?

    A pure reducer depends only on its arguments and mutates nothing, so you can log, replay and test every state change.
  2. 2. A thunk is dispatched. What does the thunk middleware do with it?

    The middleware checks whether the action is a function; if so it runs it with dispatch and getState, so the function can do async work and dispatch plain actions later.
  3. 3. A component uses useSelector(state => state.items.filter(...)) and re-renders on every store update. Why?

    React-Redux compares selected values by reference. A fresh array is never equal to the previous one; select a primitive or memoize with Reselect.
  4. 4. Which statement about Context versus Redux is accurate?

    Context only transports a value; you still hold state with useState or useReducer. Its consumers all re-render on change, whereas selectors let Redux components skip unrelated updates.
  5. 5. Why can you write state.items.push(x) inside a createSlice reducer?

    Inside createSlice reducers you receive an Immer draft. Your 'mutations' are recorded and applied to a copy, so the real state is never mutated.

Summary

  • Redux keeps all state in one store, changes it only through dispatched actions, and computes the next state with pure reducers.
  • Side effects belong in middleware; a thunk is a function that middleware calls with dispatch and getState.
  • Selectors are compared by ===; returning a new object or array each time causes needless re-renders. Memoize derived data.
  • Redux Toolkit (configureStore, createSlice, createAsyncThunk, RTK Query) is the recommended style, and Immer makes "mutating" code safe inside slices.
  • Context passes values down; it re-renders every consumer on change. Choose it for rarely changing values and Redux or another store for large, busy shared state.

Next: React Interview Questions covers Router, lifecycle, HOCs and error boundaries, and then Node.js and Backend Interview Questions is up.