React useReducer의 개념

GABMIN KIM·2022년 1월 22일
0

React

목록 보기
3/8
post-thumbnail

useReducer

const [<상태 객체>, <dispatch 함수>] = useReducer(<reducer 함수>, <초기 상태>, <초기 함수>)

useReducer는 현재 상태(state) 객체와 행동(action) 객체를 인자로 받아서 새로운 상태(state) 객체를 반환하는 함수이다. usestate와 비슷하게 상태를 관리할때 사용하지만, Hook 함수를 사용하면 컴포넌트의 상태 업데이트 로직을 컴포넌트에서 분리시킬 수 있다. 마치 상태관리 라이브러리를 활요하는 것과 유사하다.

사용 예시

import React, { useReducer } from "react";

const initalState = {
	user = "",
  	count = 0,
  	desc = "",
  // useState에서 사용했던 초기 값을 넣어준다.
}

const reducer = (state, action) => {
// state를 action을 통해 바꿔줄 내용을 적어준다.
// Switch 문을 활용하여 필요한 state에 action이 적용될 수 있도록 한다.
  switch(action.type)
    case 'SET_INCREASE':
  		return {
            ...state,
            count = action.count
        }
  //state.action = state.count 직접 변경해서는 안된다!!
  	case 'SET_DEREASE' :
  		return {
            ...state,
            count = action.count
        }
}

const onIncrease = () => {
	dispatch({type: 'SET_INCREASE', count++})
  	// dispatch ({action.type, action.count})
}

const onDecrease = () => {
	dispatch({type: 'SET_DECREASE', count--})
  	// dispatch ({action.type, action.count})
}

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

  // const [user, setUser] = useState("")
  // const [count, setCount] = useState(0)
  // const [desc, setDesc] = useState("")
  

  return (
    <div>
      <h1>{state.user}</h1> //필요한 데이터를 state를 통해 사용할 수 있다.
      <p>{state.count}</p>
      <button onClick={onIncrease}>+1</button>
      <button onClick={onDecrease}>-1</button>
    </div>
  );
}


출처

profile
목표를 성취하는 개발자가 되겠습니다.

0개의 댓글