Learn useReducer Hook, then never going back to useState

Learn useReducer Hook, then never going back to useState

·

2 min read

Before proceeding let's see the syntax for both hooks,

Now we will be implementing the 'count' logic using both hooks.

Logic:

  • step 1: First the count value is set to 0.

  • step 2: we should be able to increment and decrement the count value.

    useState Hook:

    function Counter() {
      const [count, setCount] = useState(0);
      return (
        <>
          Count: {count}
          <button onClick={() => setCount(0)}>Reset</button>
          <button onClick={() => setCount(count - 1)}>-</button>
          <button onClick={() => setCount(count + 1)}>+</button>
        </>
      );
    }
    

    where as in useReducer,

    useReducer Hook:

    const initialState = {count: 0};
    
    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();
      }
    }
    
    function Counter() {
      const [state, dispatch] = useReducer(reducer, initialState);
      return (
        <>
          Count: {state.count}
          <button onClick={() => dispatch({type: 'decrement'})}>-</button>
          <button onClick={() => dispatch({type: 'increment'})}>+</button>
        </>
      );
    }
    

    While comparing the both you will find useState easy, but whenever there is complex logic useReducer hook will come to your rescue.

  • state: It is the same as the state in useState.

  • initialState: we define the values we want to store in the state.

  • dispatch: It is a method. Basically, it sends the type of action to the reducer function to perform its job, which, of course, is updating the state, the same as the setState in the useState hook.

  • reducer: It is a function which accepts 2 arguments, state, and action, where according to the type, the action is performed.

    If you want to master React Hooks, then try using the useReducer hook from your next project onwards.

    Follow me on

    LinkedIn,

    GitHub