const [state, dispatch] = ...Write a pure function that handles state transitions based on action types.
// 1. The Reducer Function
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}Initialize `useReducer` with your reducer function and initial state. It gives you the current `state` and a `dispatch` function.
import { useReducer } from 'react';
function Counter() {
// 2. Initialize Hook
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
Count: {state.count}
{/* 3. Dispatch Actions */}
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</div>
);
}Instead of dispatching raw objects, use helper functions to keep code clean and typo-free.
// Action Types (Constants)
const ACTION = {
INCREMENT: 'INCREMENT',
DECREMENT: 'DECREMENT'
};
// Dispatch like this:
dispatch({ type: ACTION.INCREMENT });