Skip to main content

Command Palette

Search for a command to run...

Understanding the useDispatch Hook in React

Published
2 min read
S

SDE2 @Delltech • Mtech CSE'23 @IIITDelhi • Views are personal and does not represent anyone • Travel Vlogger • multi instrumentalist • singer • content creator

React is a popular JavaScript library for building user interfaces, and it comes with a set of hooks. One of these hooks is useDispatch. It’s a part of the React-Redux library, which is used for managing state in a React application.

What is useDispatch?

useDispatch is a hook that returns a reference to the dispatch function from the Redux store. You can use it to dispatch actions as needed.

Use Cases and Code Examples

Let’s look at four different use cases where useDispatch can be handy.

1. Updating a Counter

Suppose you have a counter in your application, and you want to increase or decrease the count.

import { useDispatch } from 'react-redux';

function Counter() {
  const dispatch = useDispatch();

  return (
    <div>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increase</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrease</button>
    </div>
  );
}

2. Fetching Data from an API

You can use useDispatch to dispatch an action that fetches data from an API.

import { useDispatch } from 'react-redux';

function FetchData() {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch({ type: 'FETCH_DATA' });
  }, [dispatch]);

  return <div>Fetching data...</div>;
}

3. Toggling a Theme

If your application supports light and dark themes, you can use useDispatch to toggle between them.

import { useDispatch } from 'react-redux';

function ToggleTheme() {
  const dispatch = useDispatch();

  return (
    <button onClick={() => dispatch({ type: 'TOGGLE_THEME' })}>
      Toggle Theme
    </button>
  );
}

4. Adding an Item to a Shopping Cart

In an e-commerce application, you can use useDispatch to add an item to the shopping cart.

import { useDispatch } from 'react-redux';

function AddToCart({ item }) {
  const dispatch = useDispatch();

  return (
    <button onClick={() => dispatch({ type: 'ADD_TO_CART', payload: item })}>
      Add to Cart
    </button>
  );
}

Let’s compare useDispatch() and dispatch()

AspectuseDispatch()dispatch() (Redux Store)
TypeHook provided by React ReduxFunction from the Redux store
UsageFunctional componentsAny component (class or functional)
PurposeDispatch actions to the Redux storeDispatch actions to the Redux store
Exampleconst dispatch = useDispatch();store.dispatch(yourActionCreator());
Advantages
  • Simplified syntax
  • Functional components
  • Direct access to dispatch
  • Consistency in class components
PerformanceConsider re-renders due to frequent dispatchesDirect and efficient access

More from this blog

Front end Web Development

10 posts

SE-II, Dell | IIITD | 20K Linkedin | 10K Twitter | Content creator | Multi instrumentalist |Singer | 98.11 percentile, GATECSE'21 | Featured on Times Square New York | Public Speaker | Foodie | Travel