Exercise 1: Converting Counter Component to useReducer

  1. Step 1: Set Up the Reducer Function

    
    const counterReducer = (state, action) => {
      switch (action.type) {
        case 'increment':
          return { count: state.count + 1 };
        case 'decrement':
          return { count: state.count - 1 };
        default:
          return state;
      }
    };
    
  2. Step 2: Initialize State with useReducer

    
    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;
    
    
  3. Step 3: Test the Component

  4. Step 4: Extend the Reducer

    
    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;
      }
    };