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둜 관리