Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 41 ยท Redux with React

useDispatch and Events

Learn to dispatch Redux actions from event handlers, forms, effects and child components with useDispatch. Cover payload design, batching, dispatch in effects and common mistakes, with live demos.

Reading state is half of the story. This lesson is about the other half: how components send actions. The hook is useDispatch, and the guiding idea is the one from Actions and Action Creators: a component should report what happened ("the user submitted the form") and leave the decision of what that means to a reducer.

useDispatch comes from react-redux, which our editor cannot load. As in the previous lessons, the live examples start with a block marked STAND-IN that provides createStore, Provider, useSelector and useDispatch. Slice code is written as plain hand-written reducers so that the demos run as they are.

The basic pattern

JSX
// needs react-redux (read-only here)
import { useDispatch } from 'react-redux';
import { todoAdded } from './todosSlice';

function AddTodo() {
  const dispatch = useDispatch();
  const [text, setText] = useState('');

  function handleSubmit(event) {
    event.preventDefault();
    if (!text.trim()) return;
    dispatch(todoAdded(text.trim()));
    setText('');
  }

  return (
    <form onSubmit={handleSubmit}>
      <input value={text} onChange={(e) => setText(e.target.value)} />
      <button>Add</button>
    </form>
  );
}

Three habits are visible here:

  1. Call useDispatch once per component, at the top, and use the returned dispatch in handlers.
  2. Keep form field text in local state until the user commits it. Dispatching on every keystroke fills the DevTools log with noise and re-renders every subscriber.
  3. Validate before dispatching things the UI already knows (an empty input), and let reducers enforce data rules.

dispatch is stable: the same function for the life of the store, so it is safe in dependency arrays and does not need useCallback wrapping.

Dispatching from events

Any event handler can dispatch: onClick, onChange, onSubmit, onKeyDown, onBlur, drag-and-drop, timers. Pass small payloads: an id, a value, or an object with the fields that changed.

JSX
<button onClick={() => dispatch(todoToggled(todo.id))}>Toggle</button>

<input
  defaultValue={todo.text}
  onBlur={(e) => dispatch(todoRenamed({ id: todo.id, text: e.target.value }))}
  onKeyDown={(e) => e.key === 'Escape' && dispatch(editCancelled(todo.id))}
/>
A notes list: add, edit, delete and filter

Two things to observe. The edit box commits on blur or Enter, not per key: the text being edited is local and the store only hears about the result. The filter text, in contrast, is deliberately in Redux, because another component (NoteList) needs it; that is the "shared" test from When to Use Redux.

Several dispatches, one render

You can dispatch more than once in a handler. React batches the resulting updates, so the component tree renders once after the handler finishes, not after every action. Use this to keep actions small and meaningful instead of inventing one big action that does everything. (If several actions always travel together, however, that is a hint they should be a single event that the reducers interpret.)

Batched dispatches and dispatching from an effect

After a few clicks, compare renders with the number of clicks: each click dispatches three actions but adds one render.

Dispatching from effects

An effect may dispatch, for example to say "this screen opened" or to start loading data:

JSX
useEffect(() => {
  dispatch(screenOpened('settings'));
}, [dispatch]);

Rules: never dispatch while rendering (in the component body); that changes the store during a render and React warns about it. Do not dispatch in an effect just to copy one piece of state into another (useEffect(() => dispatch(setTotal(a + b)), [a, b])); derive the value with a selector instead. In Chapter 5 you will see the usual place for effects that start requests: thunks and RTK Query.

Passing dispatch-based callbacks to children

Child components do not have to know about Redux. Hand them callbacks:

JSX
function NoteList() {
  const dispatch = useDispatch();
  const items = useSelector(selectNotes);
  return items.map((n) => (
    <NoteView key={n.id} note={n} onDelete={() => dispatch(noteRemoved(n.id))} />
  ));
}

NoteView stays reusable (and easy to test). Alternatively, let small leaf components call useDispatch themselves, which avoids prop drilling; both are accepted styles. The common guidance is to connect the components that are meaningfully tied to the app's data and keep the leaf UI components plain.

Mistakes to avoid

  • onClick={dispatch(added())}: this calls dispatch during render. Write onClick={() => dispatch(added())}.
  • Dispatching an action creator without calling it: dispatch(added) sends a function.
  • Keeping server-derived or computed values in sync with effects instead of deriving them.
  • One action per keystroke for fields nobody else reads.
  • Passing non-serializable values (event objects, DOM nodes, class instances) in payloads: send e.target.value, not e.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is wrong with <button onClick={dispatch(added())}>?

    dispatch(added()) is evaluated while rendering. Wrap it: onClick={() => dispatch(added())}.
  2. 2. Where should the text of a form field live until the user submits?

    Nobody else needs half-typed text. Local state keeps the store and DevTools quiet; dispatch the result on submit.
  3. 3. Three dispatches happen in one click handler. How many renders does React perform for the subscribed component?

    React batches updates made inside an event handler, so the tree renders once after the handler finishes.
  4. 4. Which is the right way to put a value in a payload from an input event?

    Payloads must be serializable. Send the value, not the event or the DOM node.

Summary

  • useDispatch returns a stable dispatch; call it in event handlers and effects, never during render.
  • Describe what happened with small, serializable payloads (e.target.value, not e).
  • Keep uncommitted form text in local state; keep state in Redux when other components need it.
  • Several dispatches in one handler render once; prefer a single meaningful action when they always go together.
  • Do not use effects to copy state into state: derive it with selectors.

Next: Organizing Redux Code