ReactAdvanced#hooks#state

When should you use useReducer instead of useState?

Use useReducer when several values change together, the next state depends on the previous one through many actions, or you want the update logic testable outside the component.

Example
function reducer(s, a) {
  switch (a.type) {
    case 'inc': return { ...s, n: s.n + 1 };
    default: return s;
  }
}
const [state, dispatch] = useReducer(reducer, { n: 0 });
dispatch({ type: 'inc' });

Related Questions

1
ReactIntermediate#hooks

How do you create a custom hook?

Open
2
ReactIntermediate#effects#data

How do you fetch data in a React component?

Open
3
ReactAdvanced#effects#debugging

What causes an infinite re-render loop?

Open