DEV Community

Elham Najeebullah
Elham Najeebullah

Posted on

React & TypeScript: useReducer Hook

Why use it?
useReducer is a hook that allows you to manage the state of your component in a similar way to how you would use a reducer function in Redux. It is an alternative to the useState hook and it is useful in cases where your component's state is complex and requires multiple updates based on the previous state, or when you need to handle side effects in response to state changes.

Here are some reasons why you might use useReducer:

  • Complex state: When your component's state is complex and requires multiple updates based on the previous state, useReducer can make it easier to manage. The reducer function takes the current state and an action as arguments and returns a new state based on the action. This makes it easy to handle complex state updates and ensures that the state updates are performed in a predictable and consistent way.

  • Performance: useReducer can improve the performance of your component by reducing unnecessary re-renders. When you use useState, every time you update the state, the component re-renders. However, with useReducer, you can update the state without causing the component to re-render, which can improve the performance of your application.

  • Side effects: When you need to handle side effects in response to state changes, useReducer can make it easier to manage. For example, you can use useEffect in conjunction with useReducer to handle side effects such as fetching data from an API or handling a user's input.

  • Code organization: When your component's state is complex and requires multiple updates based on the previous state, useReducer can make it easier to organize and manage the component's logic.

How to use Typescript with React

interface State {
  count: number;
}

enum ActionType {
  Increment = 'INCREMENT',
  Decrement = 'DECREMENT'
}
interface Action {
  type: ActionType;
  payload: number;
}

const initialState: State = { count: 0 };

const reducer = (state: State, action: Action) => {
  switch (action.type) {
    case ActionType.Increment:
      return { count: state.count + action.payload };
    case ActionType.Decrement:
      return { count: state.count - action.payload };
    default:
      return state;
  }
};

function MyComponent() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>{state.count}</p>
      <button onClick={() => dispatch({ type: ActionType.Increment, payload: 1 })}>
        Increment
      </button>
      <button onClick={() => dispatch({ type: ActionType.Decrement, payload: 1 })}>
        Decrement
      </button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

const [state, dispatch] = useReducer(reducer, initialState); is a way to call the React Hook useReducer and it's used to initialize the state and the dispatch function in your component.

Here's what it does step by step:

  1. useReducer is called and passed two arguments: the reducer function and the initialState object.

  2. useReducer returns an array with two elements, the first element is the current state, the second element is the dispatch function.

  3. The const [state, dispatch] destructures the returned array and assigns the first element to state and the second element to dispatch.

The state variable now contains the current state of the component and it can be used to render the component's UI. The dispatch function is used to update the state by passing an action to the reducer function.

For example, when you call dispatch({ type: 'increment', payload: 1 }) it will pass the action object to the reducer function and the reducer will update the state and return the new state.

In summary, this line of code sets up the state and the dispatch function for the component, it's the initial state of the component, the state will change as the component updates and the dispatch function is used to update the state based on the actions that are dispatched.

Top comments (0)