[react] useReducer

moo·2023년 4월 7일
0

🍳 useReducer

상태를 업데이트 할 때는 주로 useState를 사용해서 새로운 상태를 설정해준다.
useState 말고 useReducer를 사용해서도 상태를 관리할 수 있다.
useReducer를 사용하면 컴포넌트의 상태 업데이트 로직을 컴포넌트에서 분리시킬 수 있다.

❔ reducer

  • reducer는 현재 상태와 액션 객체를 파라미터로 받아와서 새로운 상태를 반환해주는 함수이다. reducer에서 반환하는 상태는 곧 컴포넌트가 지닐 새로운 상태가 된다. 여기서 action은 업데이트를 위한 정보를 가지고 있다.
function reducer(state, action) {
  // 새로운 상태를 만드는 로직
  // const nextState = ...
  return nextState;
}
//example for action
//형태에 제약은 없다.
{
  type: 'INCREMENT'
}

{
  type: 'CHANGE_INPUT',
  key: 'email',
  value: 'tester@react.com'
}

❔ useReducer 사용법

const [state, dispatch] = useReducer(reducer, initialState);
  • state : 컴포넌트에서 사용할 수 있는 상태
  • dispatch : 액션을 발생시키는 함수
    • dispatch({ type: 'INCREMENT' }) 식으로 사용한다..
  • useReducer(reducer함수 , 초기상태)

참고
https://react.vlpt.us/basic/20-useReducer.html
https://goddaehee.tistory.com/311

profile
front developer

0개의 댓글