撸了个 hook 来实现组件间 state 共享

最近刚接触 react 没多久,参考了 flutter 里的一些实现撸了个轻量级的轮子来实现组件间 state 共享:react

GitHub 仓库git

特色:github

  • 轻量级,比 redux 简单,能够在库工程里使用
  • 体积小,不足 1kb
  • 最小范围的从新渲染。例以下图 b 和 e 共享 state,当 state 值变化时只从新渲染 b 和 e:
a
+-+-+
| | |
b c d
    |
    e
  • 容许在 state 值指定字段发生变化时才从新渲染组件:
// 获取共享的 state,且在 age 字段发生变化时才更新被 hook 的组件
const state= useSharedState<User>(UserContext, (current, prev) => current?.age !== prev?.age);

核心原理:redux

  • shared state 设计为 notifier 模式
  • 使用 context hook 来在组件间共享 shared state
  • useSharedState 的 hook 实现自动注册/反注册 listener
相关文章
相关标签/搜索