frontend / state managers / redux / dispatch_function.md

Dispatch Function in Redux

4 interview angles 4 min read source

Dispatch Function in Redux

The dispatch function is a core concept in Redux that allows you to send actions to the store. It’s the only way to trigger state changes in a Redux application.

Table of Contents


What is the Dispatch Function?

  • dispatch is a function provided by the Redux store that sends actions to the store.
  • It’s the only way to trigger state changes in Redux.
  • Actions dispatched through dispatch are processed by middleware and then passed to reducers.

Signature:

dispatch(action) => action

How does Dispatch Work?

  1. Action Creation: Create a plain JavaScript object describing what happened.
  2. Dispatch: Call store.dispatch(action) to send the action to the store.
  3. Middleware Processing: Middleware can intercept, modify, or delay the action.
  4. Reducer Processing: The action reaches the reducer, which updates the state.
  5. State Update: The store’s state is updated, and subscribers are notified.

Flow:

Action → Dispatch → Middleware → Reducer → State Update → Re-render

Usage Examples

Basic dispatch:

import { createStore } from 'redux';

const store = createStore(rootReducer);

// Dispatch a simple action
store.dispatch({
  type: 'ADD_TODO',
  payload: 'Learn Redux'
});

Using action creators:

const addTodo = (text) => ({
  type: 'ADD_TODO',
  payload: text
});

store.dispatch(addTodo('Learn Redux'));

Async dispatch with thunk:

const fetchTodos = () => async (dispatch) => {
  dispatch({ type: 'FETCH_TODOS_START' });

  try {
    const response = await fetch('/api/todos');
    const todos = await response.json();
    dispatch({ type: 'FETCH_TODOS_SUCCESS', payload: todos });
  } catch (error) {
    dispatch({ type: 'FETCH_TODOS_ERROR', payload: error.message });
  }
};

store.dispatch(fetchTodos());

Different Ways to Dispatch

1. Direct dispatch from store:

const store = createStore(rootReducer);
store.dispatch({ type: 'INCREMENT' });

2. Using connect HOC:

import { connect } from 'react-redux';

const mapDispatchToProps = (dispatch) => ({
  increment: () => dispatch({ type: 'INCREMENT' })
});

const Counter = ({ increment }) => (
  <button onClick={increment}>Increment</button>
);

export default connect(null, mapDispatchToProps)(Counter);

3. Using hooks (useDispatch):

import { useDispatch } from 'react-redux';

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

  return (
    <button onClick={() => dispatch({ type: 'INCREMENT' })}>
      Increment
    </button>
  );
};

4. Using Redux Toolkit:

import { createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment: (state) => {
      state.value += 1;
    }
  }
});

const { increment } = counterSlice.actions;

// Dispatch the action
store.dispatch(increment());

Best Practices

  • Use action creators for reusable actions.
  • Keep actions serializable (no functions, promises, etc.).
  • Use descriptive action types for better debugging.
  • Dispatch actions for state changes only.
  • Use middleware for side effects (API calls, logging, etc.).

Good example:

// Action creator
const addTodo = (text) => ({
  type: 'ADD_TODO',
  payload: { id: Date.now(), text, completed: false }
});

// Dispatch
store.dispatch(addTodo('Learn Redux'));

Bad example:

// Don't dispatch non-serializable actions
store.dispatch({
  type: 'ADD_TODO',
  payload: Promise.resolve('Learn Redux') //
});

Common Interview Questions

Q: What happens if you dispatch an action that doesn’t match any reducer case?

  • The reducer returns the current state unchanged, and no state update occurs.

Q: Can you dispatch multiple actions in sequence?

  • Yes, you can call dispatch multiple times in sequence. Each action will be processed independently.

Q: What is the return value of dispatch?

  • dispatch returns the action that was dispatched.

Q: How do you handle async operations with dispatch?

  • Use middleware like redux-thunk or redux-saga to handle async operations and dispatch actions when they complete.

Q: Can you dispatch actions from within a reducer?

  • No, reducers should be pure functions and should not have side effects like dispatching actions.

Summary

  • dispatch is the only way to trigger state changes in Redux.
  • Actions dispatched through dispatch are processed by middleware and reducers.
  • Use action creators for reusable and maintainable actions.
  • Keep actions serializable and use middleware for side effects.
  • Prefer hooks (useDispatch) for functional components and connect for class components.

Interview angle

  • “What does dispatch do?” - sends an action through the middleware chain to the reducers, producing a new state, then notifies subscribers. It is the only way to change the store.
  • “How do you get it in a component?” - useDispatch(). The connect/mapDispatchToProps route is the legacy API; hooks are what the Redux docs recommend.
  • “Is dispatching synchronous?” - the dispatch and reducer run synchronously; the subscriber notification and React re-render are batched. A thunk dispatches asynchronously later, which is why “the state did not change immediately after dispatch” usually means a thunk.
  • “What must an action be?” - a plain serialisable object with a type. Putting a Promise, Date or class instance in the payload breaks time-travel debugging and persistence, and RTK’s default middleware warns about it.