擼了個 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
相關文章
相關標籤/搜索