Post

useReducer를 사용하여 useState 대체하기

1
2
3
4
5
6
const [startDate, setStartDate] = useState()
const [endDate, setEndDate] = useState()
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const [location, setLocation] = useState()
const [attendees, setAttendees] = useState([])

useState로 관리하는 상태가 많고 복잡할 때 useReducer로 대체할 수 있다.

1
2
3
4
5
6
const [event, updateEvent] = useReducer(
  (prev, next) => {
    return { ...prev, ...next }
  },
  { title: '', description: '', attendees: [] }
)

불변성을 유지하기 위해 use-immer 라이브러리를 사용할 수도 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { useImmerReducer } from 'use-immer'

function reducer(draft, action) {
  switch (action.type) {
    case 'increment':
      draft.count++
      break
    case 'decrement':
      draft.count--
      break
  }
}

function Counter() {
  const [state, dispatch] = useImmerReducer(reducer, initialState)
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </>
  )
}

참고사이트

A Cure for React useState Hell?
[번역] useState 지옥에서 벗어나기

This post is licensed under CC BY 4.0 by the author.