본문 바로가기

React

[React] useReducer 사용법

useReducer이란?

useReducer은 State(상태)를 관리하고 업데이트하는 useState를 대체할 수 있는 Hook이다.

useState로 상태를 관리하면되지 굳이 useReducer를 사용하는 이유는 뭘까?

 

useReducer 한 컴포넌트 내에서 state를 업데이트 하는 로직 부분을 그 컴포넌트로부터 분리시키는 것을 가능하게 해주는 것이다. useReducer는 state 업데이트 로직을 분리하여 컴포넌트의 외부에 작성하는 것을 가능하게 함으로써,

코드의 최적화를 이루게 해준다.

 

 

Hooks API Reference – React (reactjs.org)

 

Hooks API Reference – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

useState VS useReducer

 

* useState

     관리해야 할 state가 1개일 경우

     state가 단순한 숫자, 문자열, boolean 값일 경우

 

* useReducer 

     관리해야 할 state가 1개 이상일 경우

     state의 구조가 복잡해질 것으로 보이는 경우(큰 프로젝트)

             

          

useState

import React, { useState } from "react";

const Test9Copy = () => {                  
  const [count, setCount] = useState(0);

  const onIncrement = () => {
    setCount(count + 1)
  }

  const onDecrement = () => {
    setCount(count - 1)
  }

  const reset = () => {
    setCount(0)
  }

  return (
    <div>
      <h2> 숫자 : {count}</h2>
      <p>
        <button onClick={onIncrement}>증가:INCREMENT</button>
        <button onClick={onDecrement}>감소:DECREMENT</button>
        <button onClick={reset}>초기화:RESET</button>
      </p>
    </div>
  );
};

export default Test9Copy;

 

 

useReducer

import React, { useReducer } from "react";

//초기값
const initialState = 0;

//함수
const reducer = (state, action) => {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    case "RESET":
      return 0;
    default:
      return state;
  }
};

const Test9 = () => {                  
        //상태   액션전달자              함수       초기값
  const [count, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <h2> 숫자 : {count}</h2>
      <p>
        <button onClick={() => dispatch({type:'INCREMENT'})}>증가:INCREMENT</button>
        <button onClick={() => dispatch({type: 'DECREMENT'})}>감소:DECREMENT</button>
        <button onClick={() => dispatch({type: 'RESET'})}>초기화:RESET</button>
      </p>
    </div>
  );
};

export default Test9;

 

useReducer는 한 컴포넌트 내에서 state를 업데이트하는 로직부분을 분리시켜 컴포넌트의 최적화를 이루지만,

useState를 사용하면 클릭할때마다 별도의 함수를 만들어야 되는 복잡함이 있다.

확실히 두 코드를 비교해보면 useReducer이 간단하고 최적화된 코드로 보인다.

 

useReducer의 기본 코드 구조

 

1. 초기값, 상태분리로직 

//초기값
const initialState = {count: 0};

//상태분리로직
const reducer = (state, action) => {
  switch (action.type) {
    case '액션명':
      return 넘기는 값;
    default:
     return state
  }
}

 

 

2. useReduce

const [state, dispatch] = useReducer(reducer, initialState);
state: 상태 데이터 (이름은 사용자 정의 ex.count, num 등등)
dispatch : 액션을 발생시키는 함수(액션 전달자)
reducer : 사용자 정의함수
initialState : 초기값

 

 

3. dispatch

dispatch({type: '별칭' , 키1:값, 키2: 값})

 

 

 

<여러가지 색상 변경하는 예제>

 

import React, { useReducer } from 'react';

const initialState = {
    color:'pink'
}
const reducer = (state , action) => {
    switch( action.type) {
        case 'CHANGE_COLOR':
            return {
                color: action.step
            }
        default:
            return state 
    }
}
const Test12 = () => {
    const [ state , dispatch ] = useReducer( reducer , initialState )
    return (
        <div>
            <h1 style={{color:state.color}}>컬러 : {state.color}  </h1>
            <p>
                {/* CHANGE_COLOR */}
                <button onClick={() => dispatch({type:'CHANGE_COLOR', step:'red'})}>red</button>
                <button onClick={() => dispatch({type:'CHANGE_COLOR', step:'green'})}>green</button>
                <button onClick={() => dispatch({type:'CHANGE_COLOR', step:'blue'})}>blue</button>                
            </p>
        </div>
    );
};

export default Test12;

 

<참고자료>

https://velog.io/@iamhayoung/React-Hooks-useReducer%EC%97%90-%EB%8C%80%ED%95%B4-%EC%95%8C%EC%95%84%EB%B3%B4%EA%B8%B0

 

React Hooks :: useReducer에 대해 알아보기

React가 제공하는 내장 훅(Built-in Hooks) 중 하나인 useReducer에 대해 알아봅시다🤓

velog.io

 

반응형