MENU
Initialization
Below, the state is initialized to init(initialCount). If the third argument to useReducer(), init, is omitted, the state will simply be initialized to initialCount.
RESETRUNFULL
RESETRUNFULL
function init(initialCount) { return {count: initialCount};}function reducer(state, action) { switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement': return {count: state.count - 1};
case 'reset’
: return init(action.payload);
default
:
throw new Error(); }}function Counter({initialCount}) { const [state, dispatch] = React.useReducer(reducer, initialCount, init); return (<> Count: {state.count}
<button onClick={() => dispatch({type: 'reset', payload: initialCount})}>
Reset
</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>);}
As in useState(), if you return the same value (true Object.is(a,b)) before a dispatch, React will bail out without rendering the children or firing effects. Hence, mutating a state in place and calling setState will not cause a re-render.