React Native
useReducer vs useState
Learn the difference between useReducer and useState.
useReducer vs useState
useReducer and useState are two hooks that manage state. useState is for simple, single-value state; useReducer is for complex, related state. Both update state; but their paths differ.
In useState the update happens directly with a function: setCount(count + 1). In useReducer you send an action and the reducer computes the new state. For a simple counter useState is enough; for state with several fields like a form, a cart or a game useReducer is a better fit. When you decide, look at the complexity of state and the number of transitions.
Making the choice
When you decide which hook to pick, ask two questions. First: is the state a single value, or several related fields? Second: are the state transitions simple, or do they need complex business logic?
For a single value and simple transitions useState is a good fit. For several related fields or complex transitions useReducer is a better choice. For example a shopping cart: adding, removing, updating quantity, applying a coupon. Handling all of these with setCart gets messy; with useReducer each operation becomes an action and management gets easier.
Exercise Simple counter (useState)
Write a Counter component. Hold count with useState (initial value 0). When a button is pressed call setCount(count + 1). The component returns <Text>{count}</Text>.
Show example solution
import { useState } from "react";
import { Button, Text } from "react-native";
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<Button onPress={() => setCount(count + 1)} title="Up" />
<Text>{count}</Text>
</>
);
}
Test yourself
-
Pick the right hook
const [count, setCount] = ____(0);
Show answer
const [count, setCount] = useState(0);
-
Match the concept to its role
- useState
- Single-value state
- useReducer
- Complex state
- dispatch
- Sends an action
- reducer
- Computes state
-
Which scenario fits useReducer?
useReducer(reducer, initialState);
- A single counter
- An on/off flag
- Bir metin
- A shopping cart
Show answer
A shopping cart — A shopping cart fits useReducer.
Next lesson: Summary - useReducer