useReducer hook은 상태관리 도구이다.

useState의 대안으로 많이 사용된다.

2개 이상의 상태를 관리하기 위해서 각각을 useState로 관리하는 것 보단 useReducer를 사용하여 action별로 상태 관리하는 것이 훨씬 단순하다.

문법

1
const [state, dispatch] = useReducer(reducer, initialState);
  • useReducer는 3개의 인자를 받을 수 있다.
  • reducer 함수, initialState(초기상태), initFunction(초기화함수, optional)

예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { useReducer } from "react";
const reducer = (state, action) => {
switch (action.type) {
case "INCREMENT":
return { ...state, count: state.count + 1 };
case "DECREMENT":
return { ...state, count: state.count - 1 };
case "USER_INPUT":
return { ...state, userInput: action.payload };
case "TOGGLE_COLOR":
return { ...state, color: !state.color };
default:
throw new Error();
}
};

function App() {
const [state, dispatch] = useReducer(reducer, {
count: 0,
userInput: "",
color: false,
});

return (
<main
className="App, App-header"
style={{ color: state.color ? "#000" : "#FF07FF" }}
>
<input
style={{ margin: "2rem" }}
type="text"
value={state.userInput}
onChange={(e) =>
dispatch({ type: "USER_INPUT", payload: e.target.value })
}
/>
<br />
<br />
<p style={{ margin: "2rem" }}>{state.count}</p>
<section style={{ margin: "2rem" }}>
<button onClick={() => dispatch({ type: "DECREMENT" })}>-</button>
<button onClick={() => dispatch({ type: "INCREMENT" })}>+</button>
<button onClick={() => dispatch({ type: "TOGGLE_COLOR" })}>
Color
</button>
</section>
<br />
<br />
<p style={{ margin: "2rem" }}>{state.userInput}</p>
</main>
);
}

export default App;
  • reducer 함수에는 초기값 stateaction에 따른 case별로 반환하는 상태값을 정의한다.
  • useReducer hook을 사용하여 state(상태), dispatch(상태변경함수)를 선언한다.
  • dispatch(상태변경함수)의 인자로 객체를 전달해주는데, type, payload 프로퍼티를 갖는 객체를 전달해준다.
  • action 객체의 type에 따라 reducer에 정의해둔 action case에 따라 반환하는 값이 달라진다.
  • 위와 같이 사용하면, useStateuseState 변경함수를 여러 개 정의하지 않고도 직관적으로 상태관리 코드를 작성할 수 있다는 장점이 있다.