Reducer란

이자용·2021년 2월 3일
2

리액트

목록 보기
6/15

reducer 는 현재 상태와 액션 객체를 파라미터로 받아와서 새로운 상태를 반환해주는 함수이다.

function reducer(state, action) {
  // 새로운 상태를 만드는 로직
  // const nextState = ...
  return nextState;
}

reducer 에서 반환하는 상태는 곧 컴포넌트가 지닐 새로운 상태가 된다.


reducer 사용법

const [state, dispatch] = useReducer(reducer, initialState);

여기서 state 는 앞으로 컴포넌트에서 사용 할 수 있는 상태를 가르키게 되고, dispatch 는 액션을 발생시키는 함수라고 이해하면된다.


실제 적용

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 함수를 만들어서 'INCREMENT'와 'DECREMENT' 액션타입을 만든후 반환값으로 state값에 변화를 주었다.

Counter컴포넌트에서는 useReducer함수를 선언하여 액션타입이 포함되어있는 reducer함수와 초기값0을 인자로 넣어주고 상태값인 number와 상태를 변경할수있는 액션 dispatch액션을 비구조화할당으로 세팅해둔후에 상황에따라 액션 타입값으로 상태를 변경해주었다.

profile
이자용

0개의 댓글