[React ] useReducer Hooks

공효은·2021년 8월 19일
0

react

목록 보기
6/9

useReducer

  • 컴포넌트의 상태 업데이트 로직을 컴포넌트에서 분리시킬 수 있음
  • 상태 업데이트 로직을 컴포넌트 바깥에 작성할 수 있음
  • 상태 업데이트 로직을 다른 파일에 작성 후 불러와서 사용할 수 있음

what is Reducer❓

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

function reducer(state,action){
  //새로운 상태를 만드는 로직
  //const nextState
  
  return nextState;
}
  • nextState : reducer에서 반환하는 상태는 곧 컴포넌트가 지닐 새로운상태

  • action : 업데이트를 위한 한 정보를 가지고 있음

    • 주로 type 값을 지닌 객체 형태로 사용하지만, 꼭 따라야할 규칙은 없음

    • 예시

      //카운터에 1을 더하는 액션
      {
        type:"INCREMENT"
      }
      
      //카운터에 1을 뺴는 액션
      {
        type:"DECRREMENT"
      }
      
      //input 값을 바꾸는 액션
      {
        type:"CHANGE_INPUT",
        key:"email",
        value:"tester@react.com"
      }
      
      //새 할 일을 등록하는 액션
      {
        type:"ADD_TODO",
        todo:{
          id:1,
          text:"useReducer 배우기",
          done:false,
        }
      }

How to use UseReducer

const [state, dispatch] = useReducer(reducer,initialState);
  • state : 앞으로 컴포넌트에서 사용 할 수 있는 상태

  • dispatch : 액션을 발생시키는 함수

    • 예시 : dispatch({type:"INCREMENT"})
  • useReducer에 첫번째 파라미터는 reducer함수, 두번째 파라미터는 초기상태

Example1 (useState) Counter.js

import React, {useState} from 'react';

function Counter(){
  const [number, setNumber] = useState(0);
  
  const onIncrease = () => {
    setNumber(prevNumber => prevNumber + 1)
  } 
  
  const onDecrease = () => {
    setNumber(prevNumber => prevNumber -1)
  }
  
  return (
    <div>
    	<h1>{number}</h1>
    	<button onClick={onIncrease}>+1</button>
			<button onClick={onDecrease}>-1</button>
    </div>
  )
}

export defacult Counter;

Example2 (useReducer) Counter.js

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;

🥊useReducer vs useState

useState

  • 컴포넌트에서 관리하는 값이 딱 하나이고, 그 값이 단순한 숫자, 문자열 또는 boolean 값일때

useReducer

  • 컴포넌트에서 관리하는 값이 여러개각 되어 상태 구조가 복잡해진 경우

useReducer + Context API

https://react.vlpt.us/basic/22-context-dispatch.html

출처: https://react.vlpt.us/basic/22-context-dispatch.html

profile
잼나게 코딩하면서 살고 싶어요 ^O^/

0개의 댓글