[React] When to useReducer instead of useState

useState is typically simpler at first than useReducer (you can even implement useState using useReducer), but there's one scenario where useReducer is almost certainly better than useState:

When one element of your state relies on the value of another element of your state in order to update: useReducer

More information: KcD's blog

 

复制代码
import React from 'react'
import ReactDOM from 'react-dom'

function undoReducer(state, action) {
  const {past, present, future} = state
  const {type, newPresent} = action

  switch (type) {
    case 'UNDO': {
      if (past.length === 0) return state

      const previous = past[past.length - 1]
      const newPast = past.slice(0, past.length - 1)
      return {
        past: newPast,
        present: previous,
        future: [present, ...future],
      }
    }
    case 'REDO': {
      if (future.length === 0) return state
      const next = future[0]
      const newFuture = future.slice(1)
      return {
        past: [...past, present],
        present: next,
        future: newFuture,
      }
    }
    case 'SET': {
      if (newPresent === present) {
        return state
      }
      return {
        past: [...past, present],
        present: newPresent,
        future: [],
      }
    }
    case 'RESET': {
      return {
        past: [],
        present: newPresent,
        future: [],
      }
    }
    default: {
      throw new Error(`Unhandled action type: ${type}`)
    }
  }
}

function useUndo(initialPresent) {
  const [state, dispatch] = React.useReducer(undoReducer, {
    past: [],
    present: initialPresent,
    future: [],
  })

  const canUndo = state.past.length !== 0
  const canRedo = state.future.length !== 0

  const undo = React.useCallback(() => {
    dispatch({type: 'UNDO'})
  }, [])

  const redo = React.useCallback(() => {
    dispatch({type: 'REDO'})
  }, [])

  const set = React.useCallback(newPresent => {
    dispatch({type: 'SET', newPresent})
  }, [])

  const reset = React.useCallback(newPresent => {
    dispatch({type: 'RESET', newPresent})
  }, [])

  return [state, {set, reset, undo, redo, canUndo, canRedo}]
}

function App() {
  const [state, {set}] = useUndo('first')

  React.useEffect(() => {
    set('second')
  }, [set])

  React.useEffect(() => {
    set('third')
  }, [set])

  return <pre>{JSON.stringify(state, null, 2)}</pre>
}

ReactDOM.render(<App />, document.getElementById('root'))
复制代码

 

posted @   Zhentiw  阅读(262)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-03-11 [Algorithm] Tower Hopper Problem
2019-03-11 [Algorithm] Given the root to a binary tree, return the deepest node
2018-03-11 [HTML5] Text Alternatives
2018-03-11 [HTML5] Semantics for accessibility
2016-03-11 [RxJS] Logging a Stream with do()
2016-03-11 [RxJS] Handling a Complete Stream with Reduce
2016-03-11 [RxJS] Completing a Stream with TakeWhile
点击右上角即可分享
微信分享提示