useReducer()

김병화·2023년 1월 12일
0
const [state, dispatch] = useReducer(reducer, initialState);
  • state : 현재 상태
  • dispatch : action을 발생시키는 함수
  • reducer : state와 action를 받아 새로운 state를 반환하는 함수
  • initialState : 초기값


예시

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;
  • reducer 함수는 현재 상태(state)와 행동(action)을 인자로 받는다.
  • dispatch 함수는 액션을 발생시키는 함수이다.
  • 즉, dispatch 함수에 행동(action)을 던지면, reducer 함수가 이 행동(action)에 따라 상태(state)를 변경해준다.



참고: https://velog.io/@sdc337dc/React-useReducer

0개의 댓글