Step 1: Set Up the Reducer Function
Counter.jsx
component, replace the useState
hook with useReducer
.
const counterReducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
};
Step 2: Initialize State with useReducer
Counter
component’s state using useReducer
instead of useState
.
import React, { useReducer } from 'react';
const Counter = () => {
const [state, dispatch] = useReducer(counterReducer, { count: 0 });
return (
<div>
<h2>Counter</h2>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
};
export default Counter;
Step 3: Test the Component
Counter
component in App.jsx
.useReducer
hook is correctly managing the component’s state.Step 4: Extend the Reducer
reset
, to reset the count to 0
.Counter
component and dispatch the reset
action when it is clicked.
const counterReducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
case 'reset':
return { count: 0 };
default:
return state;
}
};