Trung BìnhReact iconReact

useReducer khác gì useState và khi nào nên dùng?

useReducer phù hợp khi state logic phức tạp với nhiều sub-values, hoặc nhiều actions khác nhau cập nhật state theo cách khác nhau.

Giống Redux pattern với dispatch/action/reducer.

tsx
type State = { count: number; step: number }
type Action = { type: 'increment' } | { type: 'setStep'; payload: number }

const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'increment': return { ...state, count: state.count + state.step }
    case 'setStep':   return { ...state, step: action.payload }
    default:          return state
  }
}

const Counter = () => {
  const [state, dispatch] = useReducer(reducer, { count: 0, step: 1 })
  return (
    <>
      <p>Count: {state.count}, Step: {state.step}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
    </>
  )
}

Xem toàn bộ React cùng filter theo level & chủ đề con.

Mở danh sách React