νλ‘ νΈμλ/React
useReducer
alswlfl
2022. 11. 24. 15:47
useReducer
- μν κ΄λ¦¬ hookμ€ νλ(useStateμ²λΌ)
- μ»΄ν¬λνΈμ μν μ λ°μ΄νΈ λ‘μ§μ μ»΄ν¬λνΈμμ λΆλ¦¬ κ°λ₯ → μν μ λ°μ΄νΈ λ‘μ§μ μ»΄ν¬λνΈ λ°κΉ₯μ μμ± κ°λ₯, μ¬μ§μ΄ λ€λ₯Έ νμΌμ μμ± ν λΆλ¬μμ μ¬μ© κ°λ₯
reducer: νμ¬ μνμ μ‘μ κ°μ²΄λ₯Ό νλΌλ―Έν°λ‘ λ°μμμ μλ‘μ΄ μνλ₯Ό λ°νν΄μ£Όλ ν¨μ
function reducer(state, action) {
// μλ‘μ΄ μνλ₯Ό λ§λλ λ‘μ§
// const nextState = ...
return nextState;
}
- λ°ννλ μνλ κ³§ μ»΄ν¬λνΈκ° μ§λ μλ‘μ΄ μνκ° λ¨
- actionμ μ λ°μ΄νΈλ₯Ό μν μ 보λ₯Ό μ§λκ³ μμ(κ°μ²΄μ ννλ μμ ) → type κ°μ μ§λ κ°μ²΄ ννλ‘ μ¬μ©
//μΉ΄μ΄ν°μ 1μ λνλ μ‘μ
{
type: 'INCREMENT'
}
//μΉ΄μ΄ν°μ 1μ λΉΌλ μ‘μ
{
type: 'DECREMENT'
}
//input κ°μ λ°κΎΈλ μ‘μ
{
type: 'CHANGE_INPUT',
key: 'email',
value: 'tester@react.com'
}
//μ ν μΌμ λ±λ‘νλ μ‘μ
{
type: 'ADD_TODO',
todo: {
id: 1,
text: 'useReducer λ°°μ°κΈ°',
done: false,
}
}
useReducer μ¬μ©λ²
const [state, dispatch] = useReducer(reducer, initialState);
- state: μ»΄ν¬λνΈμμ μ¬μ©ν μ μλ μνλ₯Ό κ°λ¦¬ν΄
- dispatch: μ‘μ μ λ°μμν€λ ν¨μ → dispatch({type: ‘INCREMENT’})
- 첫 λ²μ§Έ νλΌλ―Έν°: reducer ν¨μ
- λ λ²μ§Έ νλΌλ―Έν°: μ΄κΈ° μν
import React, { useReducer } from "react";
function reducer(state, action) {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
default:
return state;
}
}
function Counter() {
const [number, dispatch] = useReducer(reducer, 0);
const onIncrease = () => {
dispatch({ type: "INCREMENT" });
};
const onDecrease = () => {
dispatch({ type: "DECREMENT" });
};
return (
<div>
<h1>{number}</h1>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-1</button>
</div>
);
}
export default Counter;
function reducer(state, action) {
switch (action.type) {
case "CHANGE_INPUT":
return {
...state,
inputs: {
...state.inputs,
[action.name]: action.value,
},
};
default:
return state;
}
}
- reducerν¨μμμ μλ‘μ΄ μν λ§λ€ λ, λΆλ³μ± μ§μΌμ£Όμ΄μΌ ν¨ → spread μ°μ°μ μ¬μ©
useReducer vs useState
→ μν©μ λ°λΌ λ€λ¦
ex)
- μ»΄ν¬λνΈμμ κ΄λ¦¬νλ κ°μ΄ νλμ΄κ³ , κ·Έ κ°μ΄ λ¨μν μ«μ νΉμ λ¬Έμμ΄, booleanκ° → useState λ‘ κ΄λ¦¬νλ κ²μ΄ νΈλ¦¬
- μ»΄ν¬λνΈμμ κ΄λ¦¬νλ κ°μ΄ μ¬λ¬ κ°κ° λμ΄μ μνμ κ΅¬μ‘°κ° λ³΅μ‘ → useReducerλ‘ κ΄λ¦¬