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
'FA > React' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
20221105 React Hooks - Custom Hooks ์ปค์คํ ํ (0) | 2022.11.05 |
---|---|
20221103 React - ๊ฐ์๋ (Virtual DOM) (0) | 2022.11.03 |
20221102 React Hooks - useMemo, useCallback (0) | 2022.11.02 |
20221024 input type="file" ์ฉ๋ ์ ํํ๊ธฐ (0) | 2022.10.24 |
20221008 video ์ฌ์ฉํ๊ธฐ (0) | 2022.10.08 |