React Native
Action dispatch
Learn to dispatch actions with dispatch.
What is dispatch?
dispatch is the second value returned by useReducer; it is the function that sends an action. When you write dispatch({ type: "increment" }), React passes this action to the reducer and state updates.
An action is an object; usually the type property is required. Extra data can be carried too: dispatch({ type: "add", payload: 5 }). The payload field name is flexible; but the type convention is common. When dispatch is called the reducer runs, the new state is computed and the component re-renders. Binding dispatch to a button's onPress turns user input into state change.
Using dispatch
You call dispatch inside an event handler. For example you pass () => dispatch({ type: "increment" }) to a button's onPress. When the user presses the button this function runs and sends the action.
Multiple dispatch calls can be made in a row; the reducer runs separately for each. Instead of passing the action object directly to dispatch, it is also common to build it through a function first: const increment = () => dispatch({ type: "increment" }). This makes the code readable. Since an action is just an object, it is easy to test; you can call the reducer directly with an action object and check the result.
Exercise Increment with dispatch
Write a Counter component. Call useReducer with reducer and initialState (0). When a button is pressed call dispatch({ type: "increment" }). The reducer returns state + 1 in the "increment" case. The component returns <Text>{state}</Text>.
Show example solution
import { useReducer } from "react";
import { Button, Text } from "react-native";
function reducer(state, action) {
switch (action.type) {
case "increment":
return state + 1;
default:
return state;
}
}
const initialState = 0;
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
<Button onPress={() => dispatch({ type: "increment" })} title="Up" />
<Text>{state}</Text>
</>
);
}
Test yourself
-
Match each piece to its role
- dispatch
- Sends an action
- action
- Event description
- type
- Action type
- payload
- Extra data
-
Call dispatch
<Button onPress={() => ____({ type: "increment" })} title="Artır" />
Show answer
<Button onPress={() => dispatch({ type: "increment" })} title="Artır" />
-
When is dispatch called?
dispatch({ type: "increment" });
- Always inside useEffect
- When an event is detected
- Never
- Only inside the reducer
Show answer
When an event is detected — dispatch is called when an event is noticed.
Next lesson: Initial state