React性能优化

33 阅读1分钟
👨🏻‍🏫 借助本次LMS性能优化的机会,结合实际代码,找到项目中存在的无效render的case,提升对react 和性能优化的理解

定位手段

  1. react-devtools
  2. ahooks提供的 useWhyDidYouUpdate / useTrackedEffect

理论知识

  1. www.developerway.com/posts/react…
  2. www.bilibili.com/video/BV1Qx…

结合实际项目,总结的几个高频Tips

1. 如果只依赖基础变量,建议在 useSelector 内部解构,避免因为对象内其他属性变更导致非必要的update。

useSelector compares its results using strict === reference comparisons, so the component will re-render any time the selector result is a new reference! This means that if you create a new reference in your selector and return it, your component could re-render every time an action has been dispatched, even if the data really isn't different.

Bad

image.png Good

image.png

2. useSelctor中返回空对象,每次重新生成空对象,在全等判定中也是失败了,hooks会重新触发

Bad

image.png

Good

image.png

3. 自定义hooks导出function,需要添加useCallback

Bad

image.png

Good

image.png

4. 从Store或者props中获取的值,不应该再赋值给state or context

Bad

image.png

image.png image.png image.png

Good

删掉上文所有红色区域代码,都从唯一数据源store获取数据即可,慎用state状态

5. 有一些暂存变量如果不需要造成UI快速刷新,可以使用UseRef替代

Bad

image.png

Good

image.png

One More Thing

关于 context

  1. www.developerway.com/posts/how-t…