useReducer 훅 ?
- useState를 대체할 수 있는 함수
- React에서 컴포넌트의 상태 관리를 위해 기본적으로 가장 많이 쓰이는 hook은 state이다.
- 좀 더 복잡한 상태 관리가 필요한 경우 reducer를 사용할 수 있다.
( 콜백대신 dispatch를 전달할 수 있기 때문이라고 볼 수 있다.)
- reducer는 이전 상태와 Action을 합쳐, 새로운 state를 만드는 조작을 말한다.
useReducer를 사용하기 위한 구성요소 ?
1. useReducer 함수
import React, { 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
- 초기 함수 (초기 state를 조금 지연해서 생성하기 위해 사용)
2. dispatch 함수
- reducer 함수를 실행 시킨다.
- action 객체를 인자로 받으며 action 객체는 어떤 행동인지를 나타내는 type 속성과 해당 행동과 관련된 데이터(payload)를 담고 있다.
- action을 이용하여 컴포넌트 내에서 state의 업데이트를 일으킨다.
※ action은 보통 하기 샘플 예시와 같이 사용 한다.
ex1) action type만 정의하여 사용
<button onClick={() => dispatch({ type: "INCREMENT" })}>증가</button>
ex2) action type과, 데이터를 정의하여 사용
<button onClick={() => dispatch({ type: "INCREMENT", payload: 1 })}>증가</button>
3. reducer 함수
- 상기 dispatch 함수에 의해 실행되며, 컴포넌트 외부에서 state를 업데이트 하는 로직을 담당 한다.
- 함수의 인자로는 state와 action을 받게 된다.
- state와 action을 활용하여 새로운 state를 반환 한다.
ex1) action type만 정의하여 사용
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("unsupported action type: ", action.type);
}
}
ex2) action type과, 데이터를 정의하여 사용
function reducer(state, action) {
switch (action.type) {
case "INCREMENT":
return { count: state.count + action.payload };
case "DECREMENT":
return { count: state.count - action.payload };
default:
throw new Error("unsupported action type: ", action.type);
}
}
'JavaScript > React' 카테고리의 다른 글
[React] 다시보지않기 / 24시간보지않기 팝업 (0) | 2023.08.30 |
---|---|
[React] Modal창 띄워졌을 때 body 스크롤 안되게 하기 (0) | 2023.06.29 |
[React] 리액트훅스 - useReducer (0) | 2023.06.28 |
[React] useState,Props로 장바구니 기능, 상태관리 (0) | 2023.06.27 |
[React] react-cookie 로 로그아웃 기능 구현하기 (0) | 2023.06.03 |
댓글