[React] useReducer

현채은·2023년 5월 7일
0
post-thumbnail

💡 useReducer ?


  • useState를 대체할 수 있는 함수
  • React 컴포넌트의 상태 관리를 위해 기본적으로 가장 많이 쓰이는 hook ? ➡️ useState
  • 좀 더 복잡한 상태관리가 필요한 경우 reducer를 사용할 수 있다
    (콜백함수 대신 dispatch 함수를 전달할 수 있기 때문)
    • 만약 콜백함수를 이용한다면 모든 handler함수에 중복적으로 적어줘야 함..(?)
  • reducer는 이전 상태와 Action을 합쳐 새로운 state를 만드는 조작을 말함

💡 useReducer 함수


import {useReducer} from 'react';
const [state, dispatch] = useReducer(reducer, initialState,init);

1. state

  • 컴포넌트에서 사용할 상태

2. dispatch 함수

  • 첫번째 인자인 reducer를 실행시킨다.
  • 컴포넌트 내에서 state의 업데이트를 일으키기 위해 사용하는 함수

3. reducer 함수

  • 컴포넌트 외부에서 state를 업데이트하는 함수
  • 현재 state, action 객체를 인자로 받아, 기존의 state를 대체하여 새로운 state를 반환하는 함수

4. initialState

  • 초기 state

5. init

  • 초기함수

💡 dispatch 함수

  • reducer 함수를 실행시킴

  • action 객체를 인자로 받으며, action 객체는 어떤 행동인지를 나타내는 type 속성과 해당 행동과 관련된 데이터(payload) 를 담고 있음

  • action 을 이용하여 컴포넌트 내에서 state의 업데이트를 일으킴

  • action 사용 예시

<button onClick = {() => dispatch(
  {type: 'INCREMENT'}
)}> 
  증가
</button>

💡 reducer 함수

  • dispatch 함수에 의해 실행
  • 컴포넌트 외부에서 state를 업데이트하는 로직을 담당
  • 함수의 인자로는 state와 action을 받게 됨
  • state와 action을 활용하여 새로운 state를 반환해줌

①. action type만 정의한 경우

export default function reducer(state, action) {
  switch(action.type)
    case 'INCREMENT':
    	return {count: state.count +1};
  	case 'DECREMENT':
  		return {count : state.count -1};
    default :
    throw Error ("unsupported action  type: ",action.type);
  }
}
profile
프론트엔드 개발자

0개의 댓글