리액트 Hooks: 3. 사용방법2

useReducer

redux와 같이 action을 사용하여 useState보다 다양하게 state 를 조작할수 있게 해준다.

harmony
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
import React, { 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 "HANDLE_CHANGE":
return { ...state, [action.target.name]: action.target.value };
default:
return state;
}
};


const CountReducer = () => {
const [state, dispatch] = useReducer(reducer, {
count: 0,
name: "",
nickname: ""
});

const handleChange = e => {
dispatch({ type: "HANDLE_CHANGE", target: e.target });
};

return (
<div>
<p>current count: {state.count}</p>
<button onClick={() => dispatch({ type: "INCREMENT" })}>increase</button>
<button onClick={() => dispatch({ type: "DECREMENT" })}>decrease</button>
<div>
<input name="name" value={state.name} onChange={handleChange} />
<input name="name" value={state.nickname} onChange={handleChange} />
</div>
</div>
);
};

export default CountReducer;
자세히 보기
You need to set client_id and slot_id to show this AD unit. Please set it in _config.yml.