useState와 같이 상태를 변경하는 훅입니다.
import { useReducer } from 'react'
const [state, dispatch] = useReducer(reducer, initValue)
dispatch
dispatch로 보낸 값으로 reducer 함수에서 상태를 변경할 수 있습니다.
const handleIncrease = (num) => {
dispatch({
type: 'INCREASE',
payload: num,
})
}
const handleDecrease = (num) => {
dispatch({
type: 'DECREASE',
payload: num,
})
}
reducer 함수
매개변수로 state와 action을 받을 수 있습니다.
state는 initValue 가장 최신의 상태입니다.
action은 dispatch에 object로 작성한 type과 payload가 담겨있습니다.
const reducer = (state, action) => {
if(action.type === 'INCREASE') {
return state + action.num
}
if(action.type === 'DECREASE') {
return state - action.num
}
return state
}
'React' 카테고리의 다른 글
[React] vite로 프로젝트 template 만들기 (2) | 2024.12.29 |
---|---|
[React] useRef (0) | 2024.12.11 |
[React] Context API를 사용하기 전에 고려할 점 (0) | 2024.12.09 |
[React] 객체 업데이트 (0) | 2024.12.02 |
[React] 다양한 Slot 활용 방법 (1) | 2024.07.16 |