Reducer + Context: an App Store

Keep app state in a reducer at the top and share both the state and dispatch through context. Any component can read or update it.

React · intermediate · 9 min · 27 steps · free

What you'll learn

ReducerContext.jsx

import { createContext, useContext, useReducer } from 'react';

const TasksContext = createContext(null);
const DispatchContext = createContext(null);

function tasksReducer(tasks, action) {
  if (action.type === 'added') {
    return [...tasks, { id: tasks.length + 1, text: action.text }];
  }
  return tasks;
}

function AddTask() {
  const dispatch = useContext(DispatchContext);
  return <button onClick={() => dispatch({ type: 'added', text: 'Write tests' })}>Add task</button>;
}

function TaskList() {
  const tasks = useContext(TasksContext);
  return <ul>{tasks.map((t) => <li key={t.id}>{t.text}</li>)}</ul>;
}

export default function TaskApp() {
  const [tasks, dispatch] = useReducer(tasksReducer, [{ id: 1, text: 'Read the docs' }]);

  return (
    <TasksContext.Provider value={tasks}>
      <DispatchContext.Provider value={dispatch}>
        <TaskList />
        <AddTask />
      </DispatchContext.Provider>
    </TasksContext.Provider>
  );
}

Step by step

  1. React renders <TaskApp> for the first time: it calls the TaskApp function.
  2. useReducer stores the starting state and returns it: tasks = [{ id: 1, text: "Read the docs" }].
  3. TaskApp provides two contexts: the tasks, and the dispatch function. Any component inside can read either one.
  4. React renders <TaskList> for the first time: it calls the TaskList function.
  5. useContext reads the value from the nearest Provider above: tasks = [{ id: 1, text: "Read the docs" }].
  6. For t = { id: 1, text: "Read the docs" }, the callback returns <li>Read the docs</li>.
  7. TaskList returns JSX: a description of what the screen should show, <ul>…</ul>. React has not changed the page yet.
  8. React renders <AddTask> for the first time: it calls the AddTask function.
  9. AddTask reads dispatch from context. No props are needed.
  10. AddTask returns JSX: a description of what the screen should show, <button>Add task</button>. React has not changed the page yet.
  11. React turns the JSX into real page elements and shows them: look at the Screen panel.
  12. You click the “Add task” button. React calls its onClick handler.
  13. dispatch({ type: "added", … }) sends the action up to TaskApp's reducer.
  14. React renders <TaskApp> again (render 2): it calls TaskApp once more, from the top.
  15. The reducer sees the "added" action.
  16. It returns a new array with the new task.
  17. useReducer returns the latest state: tasks = [{ id: 1, text: "Read the docs" }, { id: 2, text: "Write t…].
  18. TaskApp returns JSX: a description of what the screen should show, <Provider>…</Provider>. React has not changed the page yet.
  19. React renders <TaskList> again (render 2): it calls TaskList once more, from the top.
  20. TaskList reads the new tasks from context.
  21. For t = { id: 1, text: "Read the docs" }, the callback returns <li>Read the docs</li>.
  22. For t = { id: 2, text: "Write tests" }, the callback returns <li>Write tests</li>.
  23. TaskList returns JSX: a description of what the screen should show, <ul>…</ul>. React has not changed the page yet.
  24. React renders <AddTask> again (render 2): it calls AddTask once more, from the top.
  25. useContext reads the value from the nearest Provider above: dispatch = ƒ dispatch.
  26. AddTask returns JSX: a description of what the screen should show, <button>Add task</button>. React has not changed the page yet.
  27. The new task is on the page. AddTask and TaskList never passed a prop to each other.

Common mistakes

Best practices

Key takeaways

Check yourself

Why a separate context for dispatch?

Answer: It never changes, so its readers do not re-render

Who runs the reducer?

Answer: React, when TaskApp renders