[React.js] useReducer
useReducer
useState์ ๋์ฒด ํจ์์ ๋๋ค.
(state, action) => newState์ ํํ๋ก reducer๋ฅผ ๋ฐ๊ณ (ํ์) dispatch ๋ฉ์๋์ ์ง์ ํํ๋ก ํ์ฌ state๋ฅผ ๋ฐํํฉ๋๋ค.
์ฌ์ฉํ๋ ์ด์
- ๋ค์์ ํ์๊ฐ์ ํฌํจํ๋ ๋ณต์กํ ์ ์ ๋ก์ง์ ๋ง๋๋ ๊ฒฝ์ฐ
- state๊ฐ ์ด์ state์ ์์กด์ ์ธ ๊ฒฝ์ฐ์ ๋ณดํต useState๋ณด๋ค useReducer๋ฅผ ์ ํธ
- useReducer๋ ์์ธํ ์ ๋ฐ์ดํธ๋ฅผ ํธ๋ฆฌ๊ฑฐ ํ๋ ์ปดํฌ๋ํธ์ ์ฑ๋ฅ์ ์ต์ ํํ ์ ์๊ฒ ํ๋๋ฐ, ์ด๊ฒ์ ์ฝ๋ฐฑ ๋์ dispatch๋ฅผ ์ ๋ฌ ํ ์ ์๊ธฐ ๋๋ฌธ
state : ์ํ๋ฐ์ดํฐ (์ด๋ฅผ ์์ ์ ์)
dispatch: ์ก์ ์ ๋ฐ์์ํค๋ ํจ์ (์ก์ ์ ๋ณด๋ด๋๊ณณ,์ฐ๊ฒฐ,์ ๋ฌ์)
reducer : ์ํ๋ถ๋ฆฌ๋ก์ ํจ์ (์ด๋ฆ ์์์ ์)
initialArg : ์ด๊ธฐ๊ฐ
๊ธฐ๋ณธ๊ฐ
const [state, dispatch] = useReducer(reducer, initialArg, init);
useReducer(์ํ ์
๋ฐ์ดํธ ๋ก์ง์ ๋ด์ ํจ์, ์ด๊ธฐ๊ฐ)
์ด๋ฒคํธ = dispatch({type: "์ก์
๋ช
"}) - dispatch์ ํ์
์ ํ์
์ก์
๋ช
: ๋ณ์นญ ,๋ณ๋ช
์๋ฌธ ์๋ฌธ์ ,๋๋ฌธ์ ,ํ๊ธ ๊ฐ๋ฅ / ํ์ง๋ง ๋๋ฌธ์(์์ํ)๋ก ์ฐ๋๊ฒ ์ข๋ค
dispatch({type: 'ํ์'})
dispatch({type: 'ํ์', ํค1:๊ฐ})
dispatch({type: 'ํ์', ํค1:๊ฐ, ํค2:๊ฐ})
์ํ ๋ก์ง ๋ถ๋ฆฌ
- ๊ธฐ๋ณธ ์นด์ดํธ ํจ์ ๊ตฌํ
import React from "react";
import { useReducer } from "react";
//์ด๊ธฐ๊ฐ
const initialState = 0;
//๋ถ๋ฆฌ
const reducer = (state, action) => {
switch (action.type) {
case "INCREMENT":
return state + action.step;
case "DECREMENT":
return state - action.step;
case "RESET":
return 0;
default:
return state;
}
};
const Test1_step = () => {
//์ฐ๊ฒฐ
const [count, dispatch] = useReducer(reducer, initialState);
return (
<div>
<h1>์นด์ดํธ : {count}</h1>
<p>
<button onClick={() => dispatch({ type: "INCREMENT", step: 10 })}>
10์ฉ ์ฆ๊ฐ : INCREMENT
</button>
<button onClick={() => dispatch({ type: "DECREMENT", step: 20 })}>
20์ฉ ๊ฐ์ : DECREMENT
</button>
<button onClick={() => dispatch({ type: "RESET" })}>
์ด๊ธฐํ : RESET
</button>
</p>
</div>
);
};
export default Test1_step;
- ๊ตฌํ ์์