惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
B
Blog RSS Feed
阮一峰的网络日志
阮一峰的网络日志
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
H
Help Net Security
MyScale Blog
MyScale Blog
WordPress大学
WordPress大学
Microsoft Azure Blog
Microsoft Azure Blog
GbyAI
GbyAI
小众软件
小众软件
大猫的无限游戏
大猫的无限游戏
Martin Fowler
Martin Fowler
Vercel News
Vercel News
S
SegmentFault 最新的问题
M
MIT News - Artificial intelligence
Microsoft Security Blog
Microsoft Security Blog
G
Google Developers Blog
Last Week in AI
Last Week in AI
Hugging Face - Blog
Hugging Face - Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 【当耐特】
Google DeepMind News
Google DeepMind News
Engineering at Meta
Engineering at Meta
云风的 BLOG
云风的 BLOG

Nic Lin's Blog

謝明真 - 高效領導力的課後筆記 NFT 開發實戰!基礎智能合約入門 (3) NFT 開發實戰!基礎智能合約入門 (2) NFT 開發實戰!基礎智能合約入門 (1) 如何自我檢測 log4j CVE 漏洞 Rails 如何在資料寫入時記錄來源 IP 位置 如何經營工程師 Youtube 頻道 - Part 8 營收篇 如何經營工程師 Youtube 頻道 - Part 7 酸民文化篇 如何經營工程師 Youtube 頻道 - Part 5 設備器材篇 如何經營工程師 Youtube 頻道 - Part 4 後製剪輯篇 如何經營工程師 Youtube 頻道 - Part 3 文案企劃篇 如何經營工程師 Youtube 頻道 - Part 2 設備器材篇 如何經營工程師 Youtube 頻道 - Part 1 制訂頻道方向篇 如何經營工程師 Youtube 頻道 - Part 0 Rails 中避免 race condition 的最佳實踐(二) Rails 中避免 race condition 的最佳實踐(一) 10 分鐘整合 google sheet 做自動化開發功能週報 經營 Side Project 300 天所帶來的收穫及挑戰 我的 Youtube 影片製作流程 API 設計時必須注意的 HTTP header 底線問題 如何提升你的程式可讀性之實務技巧(三) 如何提升你的程式可讀性之實務技巧(二) 如何提升你的程式可讀性之實務技巧(一) Ruby 中使用 freeze 優化效能的時機 避免 React 中的 useEffect 無限 render 在 Rails 內輕量使用 Vue Component 的最佳實踐 如何在區域網路用 Docker 架設有 SSL 的 Gitlab 從被問到問人,那些我常問的面試問題 [Rails] 如何漂亮寫出可維護的 query (Maintainable Rails Query) 在已知長度情況下優化 slice 的性能
React 效能優化基本招
Nic Lin · 2019-10-02 · via Nic Lin's Blog

會慢基本都是慢在 render function,如果巢狀 components 從父節點開始重新渲染,導致下面的子節點跟著重新 render 就會不必要的效能浪費。

所以基本招大致上是兩招,

  1. 區分何時用 Component 和 PureComponent 的時機
  2. shouldComponentUpdate 阻擋不必要渲染

PureComponent 主要是用了 shallowEqual 去做數據對比,如果沒變化就不更新。

有點像是幫你在 shouldComponentUpdate 裡面幫你先檢查好數據前後差異。

如果你的 Component 的數據經常變化,那換成 PureComponent 並不會更快,因為每次要渲染的時候都還會經過一次計算。

pure render 是指當 props 和 state 都相同時,render function 會回傳一樣的 virtual DOM。

const PostComponent = () =>
  <div>
    <PostForm>
      <h1>Create Post</h1>
    </PostForm>
  </div>

上面的寫法其實還是會一直更新 component

因為上面的程式碼等價於

const PostComponent = () =>
  <div>
    <PostForm
      children={React.createElement('h1', {}, 'Create Post')}
    />
  </div>

當 PostComponent 再次 render 時,都會呼叫 React.createElement 取得新的 element 傳給 PostForm

所以這邊 的 props.children 和 nextProps.children 永遠不同,等於沒有 pure render。

這邊可以參考套件 recompose/pure 來做 pure render 優化

類似

const PostComponent = pure(props =>
  <div>
    <PostForm>
      <h1>{props.title}</h1>
    </PostForm>
  </div>
)

這邊會用 pure 做而不全然用 shouldComponentUpdate 來做是因為,如果再一堆 component 裡面針對特定 props 更新來做渲染,其實會搞的更難以維護,因為其他開發者還需要知道「重新渲染的例外狀況」

小結

  1. 常更新 props / state 請用普通 Component 就好
  2. 不太常更新 props / state 可以用 PureComponent
  3. 嘗試用套件幫你做到 pure render
  4. 沒有 life cycle 的就可以用 Stateless Function Component

參考資源