0
0
ReactConceptBeginner · 3 min read

What is dispatch in Redux: Simple Explanation and Example

dispatch in Redux is a function used to send actions to the Redux store. It tells the store what happened so the store can update the state accordingly.
⚙️

How It Works

Imagine you have a mailbox where you send letters to tell someone what you want to happen. In Redux, dispatch is like putting a letter (called an action) into that mailbox. The Redux store reads this letter and decides how to change the state based on the message.

When you call dispatch with an action, Redux runs that action through its reducers, which are like recipe books that know how to update the state. This process keeps your app's data organized and predictable.

đź’»

Example

This example shows how to use dispatch to update a counter in a Redux store.

javascript
import { createStore } from 'redux';

// Reducer function to update state
function counterReducer(state = { count: 0 }, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

// Create Redux store
const store = createStore(counterReducer);

// Log initial state
console.log('Initial state:', store.getState());

// Dispatch increment action
store.dispatch({ type: 'increment' });
console.log('After increment:', store.getState());

// Dispatch decrement action
store.dispatch({ type: 'decrement' });
console.log('After decrement:', store.getState());
Output
Initial state: { count: 0 } After increment: { count: 1 } After decrement: { count: 0 }
🎯

When to Use

You use dispatch whenever you want to change the app's state in Redux. For example, when a user clicks a button to add an item to a shopping cart, you dispatch an action describing that event. This tells Redux to update the cart data.

It is useful in any React app that needs a clear way to handle state changes from user actions, server responses, or other events, keeping the app predictable and easier to debug.

âś…

Key Points

  • dispatch sends actions to the Redux store.
  • Actions describe what happened but don’t change state directly.
  • Reducers listen for actions and update the state accordingly.
  • Using dispatch keeps state changes predictable and traceable.
âś…

Key Takeaways

dispatch is the way to send actions to Redux to update state.
Actions describe events; reducers decide how state changes.
Use dispatch for all state changes triggered by user or system events.
It helps keep your app’s state predictable and easier to manage.