20221104 React Hooks - useReducer
Hook์ ๊ท์น
- React ํจ์ ๊ตฌ์ฑ ์์ ๋ด์์๋ง ํธ์ถํ ์ ์์(๋ฐ๋์ Functional Component ์์์ ์ฌ์ฉํด์ผ ํจ)
- ๊ตฌ์ฑ ์์์ ์ต์์์์๋ง ํธ์ถํ ์ ์์
- ์กฐ๊ฑด๋ฌธ, ๋ฐ๋ณต๋ฌธ ์์์ ๋ชป ์
useReducer
- useState์ ๋์ฒดํจ์
- ์ฝ๋ฐฑ ๋์ ๋์คํจ์น๋ฅผ ์ ๋ฌ ํ ์ ์๊ธฐ ๋๋ฌธ์ ์์ธํ ์ ๋ฐ์ดํธ๋ฅผ ํธ๋ฆฌ๊ฑฐ ํ๋ ์ปดํฌ๋ํธ์ ์ฑ๋ฅ์ ์ต์ ํ ํ ์ ์์
- useReducer๋ฅผ ์ฌ์ฉํ ๋
- ๋ค์์ ํ์๊ฐ์ ํฌํจํ๋ ๋ณต์กํ ์ ์ ๋ก์ง์ ๋ง๋๋ ๊ฒฝ์ฐ
- state๊ฐ ์ด์ state์ ์์กด์ ์ธ ๊ฒฝ์ฐ์ ๋ณดํต useState๋ณด๋ค useReducer๋ฅผ ์ ํธ
reducer : state๋ฅผ ์ ๋ฐ์ดํธ ํด์ฃผ๋ ์ญํ
dispatch: state ์ ๋ฐ์ดํธ๋ฅผ ์ํ ์๊ตฌ
action: ์๊ตฌ์ ๋ด์ฉ
๋์คํจ์น๋ก ์ก์ (์๊ตฌ,์กฐ๊ฑด)์ ํจ > ๋ฆฌ๋์์๋ฅผ ํตํด์ > ์คํ ์ดํธ๊ฐ ์ ๋ฐ์ดํธ
dispatch(Actoin) > Reducer(State, Action) > State Update
import { useReducer } from "react";
const [state, dispatch] = useReducer(reducer, initialArg, init);
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
์ฐธ๊ณ ์๋ฃ ๋ฐ ์ถ์
https://ko.reactjs.org/docs/hooks-reference.html#usereducer
Hooks API Reference – React
A JavaScript library for building user interfaces
ko.reactjs.org
https://www.w3schools.com/react/react_usereducer.asp
React useReducer Hook
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com