CodeBlanks Logo Icon CodeBlanks

useDispatch

Learn to dispatch actions with useDispatch.

useDispatch

useDispatch is a hook from react-redux. It is used to send an action from inside a component. You get the dispatch function with const dispatch = useDispatch(); then you call dispatch(increment()). Dispatch delivers the action to the store; the relevant reducer runs and state updates.

Important: you must call the action creator to produce an object. dispatch(increment) is wrong; dispatch(increment()) is right. Because increment() returns the object { type: 'counter/increment' } and dispatch expects this object.

A button with useDispatch

In a typical use you dispatch inside a button's onPress event. First get dispatch with useDispatch, then write onPress={() => dispatch(increment())}. This way each press sends the counter/increment action and the counter grows.

If you have several action creators you can import all of them at the top: import { increment, decrement } from './counterSlice'. Dispatch calls grow with the number of buttons; each sends a different action.

Practice A dispatch button

Complete the CounterButton component. Import useDispatch. Get the increment action creator from ./counterSlice. In the button's onPress call dispatch(increment()).

Starter code

App.js
import React from 'react';
import { Button } from 'react-native';

export function CounterButton() {
  // get dispatch and call increment on button onPress

  return null;
}

Sample solution

App.js
import React from 'react';
import { Button } from 'react-native';
import { useDispatch } from 'react-redux';
import { increment } from './counterSlice';

export function CounterButton() {
  const dispatch = useDispatch();

  return (
    <Button title="Increase" onPress={() => dispatch(increment())} />
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why is dispatch(increment) wrong?

  • Because increment() must be called
  • Because dispatch takes no argument
  • Because hooks cannot be used Correct answer
  • Because increment is a number

Explanation: You must call the action creator to produce an object.

2 Match the dispatch parts

Term Meaning
useDispatch Provides the dispatch function
increment() Produces the action object
dispatch(...) Sends the action to the store
onPress Triggers the event

3 The action creator call

Question
onPress={() => dispatch(____())}
Answer
onPress={() => dispatch(increment())}

Explanation: increment() returns the action object.

All lessons in Advanced