useReducer vs useState
- React Native course
- Intermediate
- Lesson 28/116
- 5 min
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.
Practice 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>.
Starter code
// Import useState
// Import Text and Button from react-native
function Counter() {
// Start count state with useState; initial 0
// On button press raise the number by one
return <Text>Counter</Text>;
}Sample 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>
</>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Pick the right hook
const [count, setCount] = ____(0);
const [count, setCount] = useState(0);
Explanation: useState is enough for a simple counter.
2 Match the concept to its role
| Term | Meaning |
|---|---|
useState |
Single-value state |
useReducer |
Complex state |
dispatch |
Sends an action |
reducer |
Computes state |
3 Which scenario fits useReducer?
useReducer(reducer, initialState);- A single counter
- An on/off flag
- Bir metin
- A shopping cart Correct answer
Explanation: A shopping cart fits useReducer.