useReducer
ํ์ต ํค์๋
useReducer
๐ useReducer
useReducer๋ ์ปดํฌ๋ํธ์ reducer๋ฅผ ์ถ๊ฐํ ์ ์๊ฒ ํด์ฃผ๋ React Hook
reducer๋ฅผ ์ฌ์ฉํ์ฌ ์ปดํฌ๋ํธ์ ์ํ ๋ก์ง์ ๊ด๋ฆฌํ๋ ๋ฐ ์ฌ์ฉ๋๋ค.
์ฃผ๋ก useState๋ณด๋ค ๋ณต์กํ ์ํ ๋ก์ง์ ์ฒ๋ฆฌํด์ผํ ๋ ์ฌ์ฉํ๋ค.
์ปดํฌ๋ํธ ์ธ๋ถ์์ State ๊ด๋ฆฌ ๋ก์ง ๋ถ๋ฆฌ ๊ฐ๋ฅ
๐ค useReducer ์ฌ์ฉ๋ฒ
const [state, dispatch] = useReducer(reducer, initialArg, init?)
import { useReducer } from 'react';
function reducer(state, action) {
// ...
}
function MyComponent() {
const [state, dispatch] = useReducer(reducer, { age: 42 });
// ...
}
Parameter
reducer ํจ์
: ์ํ๊ฐ ์ด๋ป๊ฒ ์ ๋ฐ์ดํธ๋ฅผ ํ ์ง๋ฅผ ๋ช ์ํด๋ ํจ์.์์ํจ์
์ธ์๋ก state, Action์ ์ ๋ฌํ๋ฉด ์๋ก์ด ์ํ (state)๊ฐ์ ๋ฐํํ๋ค.
initialArg
: ์ด๊ธฐ๊ฐ์ด๊ธฐ ์ํ๋ฅผ ๊ณ์ฐํ๋ ๋ฐฉ๋ฒ์ ๋ค์ init ์ธ์์ ๋ฐ๋ผ ๋ฌ๋ผ์ง๋ค.
init(์ ํ์ฌํญ)
: ์ด๊ธฐ๊ฐ์ ๋ฐํํ๋ ์ด๊ธฐํ ํจ์์ด๊ธฐํ ํจ์๊ฐ ์ ๋ฌ๋์ง ์์ ๊ฒฝ์ฐ, ์ด๊ธฐ ๊ฐ์ initialArg ๊ฐ์ผ๋ก ์ค์ ๋๋ค.
๊ทธ๋ ์ง ์์ ๊ฒฝ์ฐ, ์ด๊ธฐ๊ฐ์ init(initialArg)๋ฅผ ํธ์ถํ ๊ฒฐ๊ณผ๋ก ์ค์ ๋๋ค.
reducer ํจ์๋ ๋ฐ๋์ ๋ถ๋ณ์ฑ์ ์ง์ผ ์๋ก์ด ์ํ๋ฅผ ๋ฐํ ํด์ผํ๋ค.
function reducer(state, action) {
switch(action.type){
case 'Action.Type' : {
return {...state, name:'New Name'} // ์คํ๋ ๋ ๋ฌธ๋ฒ์ ์ฌ์ฉํ์ฌ ๊ธฐ์กด state์ ๋ถ๋ณ์ฑ์ ์ ์ง
}
}
}
Returns
useReducer๋ ๋ ๊ฐ์ ๊ฐ์ง๋ ๋ฐฐ์ด์ ๋ฐํํ๋ค.
state
: ์ฒซ ๋ฒ์งธ ๋ ๋ ์ค init(initialArg) ๋๋ initialArg๋ก ์ค์ dispatch ํจ์
: ์ํ๋ฅผ ๋ค๋ฅธ ๊ฐ์ผ๋ก ์ ๋ฐ์ดํธํ๊ณ ์ฌ๋ ๋๋ฅผ ๋ฐ์์ํค๋ ํจ์ (์ํ๋ณํ๋ฅผ ๋ฐ๋์ํค๋ ํธ๋ฆฌ๊ฑฐ ์ญํ)์ธ์๋ก Action ์ ๋ฌ
dispatch ํจ์ ์ํ๋ฅผ ๋ค๋ฅธ ๊ฐ์ผ๋ก ์ ๋ฐ์ดํธํ๊ณ ์ฌ๋ ๋๋ฅผ ๋ฐ์์ํจ๋ค. dispatch ํจ์์ ์ ์ผํ ์ธ์๋ก ์ก์ ์ ์ ๋ฌํ๋ค.
const [state, dispatch] = useReducer(reducer, { age: 42 });
function handleClick() {
dispatch({ type: 'incremented_age' });
// ...
๐ ์ฐธ๊ณ
Last updated