import { useReducer } from 'react'; // 1. Define initial state const initialState = { count: 0, showText: true }; // 2. Define reducer function function reducer(state, action) { switch (action.type) { case 'increment': return { ...state, count: state.count + 1 }; case 'decrement': return { ...state, count: state.count - 1 }; case 'reset': return { ...state, count: action.payload || 0 }; case 'toggleText': return { ...state, showText: !state.showText }; default: throw new Error(); } } // 3. Component using useReducer function CounterWithReducer() { const [state, dispatch] = useReducer(reducer, initialState); return (

Count: {state.count}

{state.showText &&

This text can be toggled!

}
); }