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
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>
);
}<TaskApp> for the first time: it calls the TaskApp function.useReducer stores the starting state and returns it: tasks = [{ id: 1, text: "Read the docs" }].<TaskList> for the first time: it calls the TaskList function.useContext reads the value from the nearest Provider above: tasks = [{ id: 1, text: "Read the docs" }].t = { id: 1, text: "Read the docs" }, the callback returns <li>Read the docs</li>.TaskList returns JSX: a description of what the screen should show, <ul>…</ul>. React has not changed the page yet.<AddTask> for the first time: it calls the AddTask function.dispatch from context. No props are needed.AddTask returns JSX: a description of what the screen should show, <button>Add task</button>. React has not changed the page yet.onClick handler.dispatch({ type: "added", … }) sends the action up to TaskApp's reducer.<TaskApp> again (render 2): it calls TaskApp once more, from the top.useReducer returns the latest state: tasks = [{ id: 1, text: "Read the docs" }, { id: 2, text: "Write t…].TaskApp returns JSX: a description of what the screen should show, <Provider>…</Provider>. React has not changed the page yet.<TaskList> again (render 2): it calls TaskList once more, from the top.t = { id: 1, text: "Read the docs" }, the callback returns <li>Read the docs</li>.t = { id: 2, text: "Write tests" }, the callback returns <li>Write tests</li>.TaskList returns JSX: a description of what the screen should show, <ul>…</ul>. React has not changed the page yet.<AddTask> again (render 2): it calls AddTask once more, from the top.useContext reads the value from the nearest Provider above: dispatch = ƒ dispatch.AddTask returns JSX: a description of what the screen should show, <button>Add task</button>. React has not changed the page yet.Answer: It never changes, so its readers do not re-render
Answer: React, when TaskApp renders