CAFECA-IO / TideBit-DeFi

TideBit Decentralize Finance Version
https://tidebit-defi.vercel.app
GNU General Public License v3.0
1 stars 0 forks source link

比較 Zustand 跟 Context API with Event 的優劣 #1459

Closed arealclimber closed 9 months ago

arealclimber commented 9 months ago

reference

arealclimber commented 9 months ago

TBD

藍字跟紅字分別為不同的 context ,彼此平行,但能透過 event 溝通,一方 event.emit(),另一方 event.on(),達成 context 之間的數據交流,不需要大幅度重構架構就能解決減少不必要元件重新渲染的問題

image

arealclimber commented 9 months ago

Context + event emitter vs Zustand 綜合比較


  1. 簡易性與學習曲線:
    • Context + Event Emitter: React 的 Context API 用於跨組件共享狀態,而 Event Emitter 用於跨組件事件通訊。這種組合可能需要更多的模板代碼(event.emit, event.on)。
    • Zustand: Zustand 是一個簡潔且輕量的狀態管理庫,易於學習和使用。它提供了一種更直接和簡化的方式來處理全局狀態。
  2. 性能和最佳化:
    • Context + Event Emitter: React Context 在更新時可能導致不必要的組件重新渲染,但可以藉由更精確的 context 分割,將高頻更新的 context 拆出來,避免重複渲染不必要的組件。
    • Zustand: Zustand 優化了狀態的選擇和更新,減少了不必要的渲染。它允許組件訂閱特定的狀態片段,提高了性能。
  3. 模塊化和可維護性:
    • Context + Event Emitter: 在大型專案中,使用 Context 和 Event Emitter 可能需要更精心的架構設計來確保代碼的可維護性和模塊化。
    • Zustand: Zustand 支持將狀態分割成小的、獨立的存儲,Zustand 就像是將 context + event 的方法包好提供開發者使用,可以提高代碼可讀性,這有助於模塊化和維護大型專案。
  4. 靈活性和擴展性:
    • Context + Event Emitter: 這種方法提供了高度的靈活性和自定義能力,可以根據專案需求定制狀態管理和事件通訊的方式。
    • Zustand: 是一個預定義的庫,可能無法涵蓋所有自定義的狀態管理需求。