useReducer 사용법

이수빈·2023년 10월 12일
1

React

목록 보기
7/20
post-thumbnail

useReducer?

  • state 를 관리하고 업데이트 하는 hook 인 useState 를 대체 할 수 있는 hook 입니다.

  • 즉, useReducer 는 useState 처럼 state 를 관리하고 업데이트 할 수 있는 hook 입니다.
    Redux 가 돌아가는 구조랑 비슷함 (Observer 패턴)

사용방법? 이유?

params

  • Reducer => 컴포넌트 외부에서 state를 업데이트 하는 함수, 현재 state, action 객체를 인자로 받아, 기존의 state를 대체하여 새로운 state를 반환하는 함수 
  • initialArg => initialState(초기 State값)
  • init =>  초기함수(초기 state를 조금 지연해서 생성하기 위해 사용) , optional

return

  • state => 컴포넌트에서 사용할 상태
  • dispatch 함수 => Reducer함수를 실행시킴. 컴포넌트 내에서 state의 업데이트를 일으키기 위해 사용하는 함수
  • action 객체를 인자로 받으며 action 객체는 어떤 행동인지를 나타내는 type 속성과 해당 행동과 관련된 데이터(payload)를 담고 있다.
//useState를 이용해 구현한 Counter

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  const decrement = () => {
    setCount(count - 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

export default Counter;


// useReducer를 사용해 구현한 카운터


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

// (state, action) => newState 의 형태로 reducer를 받음.
// 상태를 관리하려는 공통 조상부모 컴포넌트에서 선언함.

 const initialState = {count: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

//  reducer 파일을 따로 분리

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}
 

초기화 지연 (세번째 parameter 사용방법)

  • 초기 state가 고정적이지 않을때, 함수형태로 초기 state를 한번 가공해서 사용 할 수 있음.
  • 초기값을 만드는 함수로도 로직의 재사용가능
function init(initialCount) {
  return {count: initialCount};
}

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    case 'reset':
      return init(action.payload);
    default:
      throw new Error();
  }
}
 

사용이유?

  • state와의 차이점 => 상태가 복잡해지거나 커지면, reducer를 사용해서 효율적인 코드를 작성할 수 있음.

  • state와 비교했을때 장점 => reducer 로직의 분리(비즈니스 로직 분리가능) 

  • 다수의 하윗값을 포함하는 복잡한 정적로직을 만들거나, 다음 state가 이전 state에 의존적인 경우 사용이 선호됨 => callback대신 dispatch를 통해 상태를 update함

ref) 

https://choi-hyunho.tistory.com/196
https://ko.legacy.reactjs.org/docs/hooks-reference.html#usereducer
https://goddaehee.tistory.com/311
https://velog.io/@goldbear2022/setInterval-%ED%8A%B9%EC%A7%95%EA%B3%BC-useInterval

profile
응애 나 애기 개발자

0개의 댓글