Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 41 ยท Projects and Practice

Redux Practice Exercises

Practice Redux with hands-on exercises: write a reducer, a memoized selector, a logging middleware and a thunk. Each runnable starter has checks, followed by full solutions.

Reading about Redux is not the same as writing it. These exercises cover the skills from the whole course: reducers, selectors, middleware and async thunks. Each starter below runs and prints FAIL lines until you fill in the missing code. Try each one before you open its solution.

All code uses hand-written stand-ins for the store (the Redux packages are not available in the editors), so the logic is the same as in a real project but dependency-free.

Work in this order: read the task, run the starter (all checks fail), write your solution in the editor, run again until every line says PASS. Only then compare with the solution.

Exercise 1: a counter reducer with limits

Write counter(state, action). The state is { value, step } (start { value: 0, step: 1 }). Handle:

  • inc adds step, dec subtracts step.
  • setStep with a payload sets step (ignore values below 1).
  • reset returns the initial state.
  • The value never goes below 0 or above 10.
  • Return the same state object if nothing changes (for example dec at 0).
JS Exercise 1: starter

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

No output.

Exercise 2: a memoized selector

Write createMemo(fn) that remembers the last arguments and result (compare arguments with ===), then use it for selectExpensiveTotal. It must recompute only when the items array reference changes, not when user changes.

JS Exercise 2: starter

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

No output.

Exercise 3: a rate-limiting middleware

Write middleware that lets at most 2 actions of type message/sent through per "window". Extra ones must be dropped (not passed to next). After window/reset is dispatched the counter starts again. All other actions pass through untouched.

JS Exercise 3: starter

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

No output.

Exercise 4: a thunk with caching

Write loadUser(id). It must dispatch user/pending, then user/fulfilled with the user. If the user is already in the state it must not call the API or dispatch anything. If the API throws, dispatch user/rejected with the error message. The thunk must return 'cached', 'loaded' or 'failed'.

JS Exercise 4: starter

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

No output.

Solutions

Solution 1

JS Exercise 1: solution

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

No output.

The key idea: compute the candidate value, then compare with the old one and return the old state object when nothing changed. That is what keeps subscribers quiet.

Solution 2

JS Exercise 2: solution

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

No output.

Solution 3

JS Exercise 3: solution

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

No output.

State that belongs to the middleware (the counter) lives in a closure, not in the Redux state, because it is about the pipeline, not about your app's data. Keep such state small and reset it deliberately.

Solution 4

JS Exercise 4: solution

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

No output.

More challenges

  1. Undo for the cart. Wrap the cart slice from the shopping cart project with withHistory from undo/redo, but make checkout clear the history.
  2. Normalize an API. Take a nested response of authors, books and reviews and normalize it into three tables, then write selectors that join them back (state shape).
  3. Optimistic toggle. Write a thunk that toggles a todo immediately, calls a fake API and restores the old value if the API fails.
  4. Listener. Using the listener idea from custom middleware, save the todos to a fake API 500 ms after the last change.
  5. Port a legacy reducer. Convert a switch-based reducer with constants to a slice shape (migration) and prove with tests that both behave the same.
  6. Performance hunt. In a stand-in useSelector (see re-renders), find which of five selectors causes a render on every dispatch, and fix it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A reducer receives an action it does not handle. What should it return?

    Returning the same reference tells subscribers nothing changed.
  2. 2. Where should the counter of a rate-limiting middleware live?

    It is not application data, so it does not belong in the store.
  3. 3. A thunk finds the data already in the state. What should it do?

    Checking getState() first avoids duplicate requests.
  4. 4. Why compare memoized arguments with === rather than deep equality?

    Immutability makes reference checks a reliable and cheap change detector.

Summary

  • You wrote a reducer that preserves identity, a memoizer, a middleware and a caching thunk.
  • Return the same state object when nothing changes.
  • Keep pipeline state in closures and application data in the store.
  • Thunks check getState() first, then dispatch status actions around the async call.
  • Keep practicing: the challenges above build on every earlier lesson.

Next: Back to the Redux track