Sub topic 1
Where useState starts to strain
Prerequisites
Assume you know JavaScript functions, objects, arrays, spread syntax, React function components, JSX, props, event handlers, and the useState hook.
Where `useState` starts to strain
useState works well when a component has a few independent values. It becomes harder to follow when several values change together or when many event handlers repeat update logic.
For example, a todo editor might update the list, the selected item, and an error message. Each handler must know which values to change and how those values relate. A reducer gives these changes one central place.
Writing a reducer function
A reducer is a pure function with this shape:
(state, action) => nextStateIt receives the current state and an action describing what happened. It returns the next state. A pure function does not modify its arguments or perform side effects such as network requests.
function counterReducer(state, action) {
switch (action.type) {
case 'incremented':
return { count: state.count + 1 };
case 'reset':
return { count: 0 };
default:
throw Error('Unknown action: ' + action.type);
}
}The reducer does not handle a click directly. It defines the result of each supported state transition.
Describing changes with actions
An action is usually an object with a type property. Its other properties carry the data needed for the transition.
dispatch({ type: 'incremented' });
dispatch({ type: 'reset' });
dispatch({ type: 'set', value: 10 });The component reports an event by dispatching an action. The reducer interprets that action. This separates the event source from the state-update rules.
Updating objects and arrays immutably
Reducers must return new objects or arrays instead of changing the existing state. Use spread syntax, map, and filter.
function todosReducer(todos, action) {
switch (action.type) {
case 'added':
return [...todos, { id: action.id, text: action.text, done: false }];
case 'toggled':
return todos.map(todo =>
todo.id === action.id ? { ...todo, done: !todo.done } : todo
);
case 'deleted':
return todos.filter(todo => todo.id !== action.id);
default:
throw Error('Unknown action: ' + action.type);
}
}New references let React detect that state changed. Mutating an existing array can hide changes and produce stale or unpredictable renders.
Exercise
Why should a reducer return a new array when adding a todo?
Show answer
A new array preserves the old state and gives React a changed reference to detect.