Skip to content
This repository was archived by the owner on Feb 27, 2026. It is now read-only.

Commit 538cfe3

Browse files
committed
Create react hook for useReducer hook
1 parent a59e0a1 commit 538cfe3

1 file changed

Lines changed: 92 additions & 0 deletions

File tree

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
---
2+
Title: 'useReducer()'
3+
Description: 'Allows you to add a reducer to your component.'
4+
Subjects:
5+
- 'Web Development'
6+
Tags:
7+
- 'Components'
8+
- 'React'
9+
CatalogContent:
10+
- 'react-101'
11+
- 'paths/front-end-engineer-career-path'
12+
---
13+
14+
The **`useReducer()`** hook in React allows for custom state logic. If you find yourself keeping track of multiple pieces of state that rely on complex logic, **`useReducer()`** may be useful. It allows you add a reducer to your component. It takes in the reducer function and an initialState as arguments. The **`useReducer()`** also returns an array of the current state and a dispatch function.
15+
16+
## Syntax
17+
18+
The `useReducer()` hook accepts three arguments.
19+
20+
```pseudo
21+
useReducer(reducer, initialState, init)
22+
```
23+
24+
The `reducer` function contains your custom state logic and the `initialStatecan` be a simple value, but generally will contain an object. The `init` argument is optional and is used to initialize the state.
25+
26+
The `useReducer` Hook returns the current `state` and a `dispatch` method.
27+
28+
## Example 1
29+
30+
In this example, we use `useReducer` to keep track of the score of two players.
31+
32+
```jsx
33+
import { useReducer } from 'react';
34+
import { createRoot } from 'react-dom/client';
35+
36+
const initialScore = [
37+
{
38+
id: 1,
39+
score: 0,
40+
name: "John",
41+
},
42+
{
43+
id: 2,
44+
score: 0,
45+
name: "Sally",
46+
},
47+
];
48+
49+
const reducer = (state, action) => {
50+
switch (action.type) {
51+
case "INCREASE":
52+
return state.map((player) => {
53+
if (player.id === action.id) {
54+
return { ...player, score: player.score + 1 };
55+
} else {
56+
return player;
57+
}
58+
});
59+
default:
60+
return state;
61+
}
62+
};
63+
64+
function Score() {
65+
const [score, dispatch] = useReducer(reducer, initialScore);
66+
67+
const handleIncrease = (player) => {
68+
dispatch({ type: "INCREASE", id: player.id });
69+
};
70+
71+
return (
72+
<>
73+
{score.map((player) => (
74+
<div key={player.id}>
75+
<label>
76+
<input
77+
type="button"
78+
onClick={() => handleIncrease(player)}
79+
value={player.name}
80+
/>
81+
{player.score}
82+
</label>
83+
</div>
84+
))}
85+
</>
86+
);
87+
}
88+
89+
createRoot(document.getElementById('root')).render(
90+
<Score />
91+
);
92+
```

0 commit comments

Comments
 (0)