这才是 React Hooks 性能优化的正确姿势

开发 前端
React Hooks 出来很长一段时间了,相信有不少的朋友已经深度使用了。无论是 React 本身,还是其生态中,都在摸索着进步。

[[433487]]

React Hooks 出来很长一段时间了,相信有不少的朋友已经深度使用了。无论是  React 本身,还是其生态中,都在摸索着进步。鉴于我使用的  React 的经验,给大家分享一下。对于  React hooks ,性能优化可以从以下几个方面着手考虑。

场景1

在使用了 React Hooks 后,很多人都会抱怨渲染的次数变多了。没错,官方就是这么推荐的:

我们推荐把 state 切分成多个  state 变量,每个变量包含的不同值会在同时发生变化。

  1. function Box() { 
  2.   const [position, setPosition] = useState({ left: 0, top: 0 }); 
  3.   const [size, setSize] = useState({ width: 100, height: 100 }); 
  4.   // ... 

这种写法在异步的条件下,比如调用接口返回后,同时 setPosition 和  setSize ,相较于 class 写法会额外多出一次  render 。这也就是渲染次数变多的根本原因。当然这种写法仍然值得推荐,可读性和可维护性更高,能更好的逻辑分离。

针对这种场景若出现十几或几十个 useState 的时候,可读性就会变差,这个时候就需要相关性的组件化了。以逻辑为导向,抽离在不同的文件中,借助  React.memo 来屏蔽其他  state 导致的  rerender 。

  1. const Position = React.memo(({ position }: PositionProps) => { 
  2.  
  3. // position 相关逻辑 
  4.  
  5. return ( 
  6.  
  7. <div>{position.left}</div> 
  8.  
  9. ); 
  10.  
  11. }); 

因此在 React hooks 组件中尽量不要写流水线代码,保持在 200 行左右最佳,通过组件化降低耦合和复杂度,还能优化一定的性能。

场景2

class 对比  hooks ,上代码:

  1. class Counter extends React.Component { 
  2.  
  3. state = { 
  4.  
  5. count: 0
  6.  
  7. }; 
  8.  
  9. increment = () => { 
  10.  
  11. this.setState((prev) => ({ 
  12.  
  13. count: prev.count + 1
  14.  
  15. })); 
  16.  
  17. }; 
  18.  
  19. render() { 
  20.  
  21. const { count } = this.state; 
  22.  
  23. return <ChildComponent count={count} onClick={this.increment} />; 
  24.  
  25.  
  26.  
  27. function Counter() { 
  28.  
  29. const [count, setCount] = React.useState(0); 
  30.  
  31. function increment() { 
  32.  
  33. setCount((n) => n + 1); 
  34.  
  35.  
  36. return <ChildComponent count={count} onClick={increment} />; 
  37.  

凭直观感受,你是否会觉得 hooks 等同于  class 的写法?错, hooks 的写法已经埋了一个坑。在  count 状态更新的时候,  Counter 组件会重新执行,这个时候会重新创建一个新的函数  increment 。这样传递给  ChildComponent 的  onClick 每次都是一个新的函数,从而导致  ChildComponent 组件的  React.memo 失效。

解决办法:

  1. function usePersistFn<T extends (...args: any[]) => any>(fn: T) { 
  2.  
  3. const ref = React.useRef<Function>(() => { 
  4.  
  5. throw new Error('Cannot call function while rendering.'); 
  6.  
  7. }); 
  8.  
  9. ref.current = fn; 
  10.  
  11. return React.useCallback(ref.current as T, [ref]); 
  12.  
  13.  
  14. // 建议使用 `usePersistFn` 
  15.  
  16. const increment = usePersistFn(() => { 
  17.  
  18. setCount((n) => n + 1); 
  19.  
  20. }); 
  21.  
  22. // 或者使用 useCallback 
  23.  
  24. const increment = React.useCallback(() => { 
  25.  
  26. setCount((n) => n + 1); 
  27.  
  28. }, []); 

上面声明了 usePersistFn 自定义  hook ,可以保证函数地址在本组件中永远不会变化。完美解决  useCallback 依赖值变化而重新生成新函数的问题,逻辑量大的组件强烈建议使用。

不仅仅是函数,比如每次 render 所创建的新对象,传递给子组件都会有此类问题。尽量不在组件的参数上传递因  render 而创建的对象,比如  style={{ width: 0 }} 此类的代码用  React.useMemo 或  React.memo 编写  equal 函数来优化。

style 若不需改变,可以提取到组件外面声明。尽管这样做写法感觉太繁琐,但是不依赖  React.memo 重新实现的情况下,是优化性能的有效手段。

  1. const style: React.CSSProperties = { width: 100 }; 
  2.  
  3. function CustomComponent() { 
  4.  
  5. return <ChildComponent style={style} />; 
  6.  

场景3

对于复杂的场景,使用 useWhyDidYouUpdate hook 来调试当前的可变变量引起的  rerender 。这个函数也可直接使用  ahooks 中的实现。

  1. function useWhyDidYouUpdate(name, props) { 
  2.  
  3. const previousProps = useRef(); 
  4.  
  5. useEffect(() => { 
  6.  
  7. if (previousProps.current) { 
  8.  
  9. const allKeys = Object.keys({ ...previousProps.current, ...props }); 
  10.  
  11. const changesObj = {}; 
  12.  
  13. allKeys.forEach(key => { 
  14.  
  15. if (previousProps.current[key] !== props[key]) { 
  16.  
  17. changesObj[key] = { 
  18.  
  19. from: previousProps.current[key], 
  20.  
  21. to: props[key] 
  22.  
  23. }; 
  24.  
  25.  
  26. }); 
  27.  
  28. if (Object.keys(changesObj).length) { 
  29.  
  30. console.log('[why-did-you-update]', name, changesObj); 
  31.  
  32.  
  33.  
  34. previousProps.current = props; 
  35.  
  36. }); 
  37.  
  38.  
  39. const Counter = React.memo(props => { 
  40.  
  41. useWhyDidYouUpdate('Counter', props); 
  42.  
  43. return <div style={props.style}>{props.count}</div>; 
  44.  
  45. }); 

当 useWhyDidYouUpdate 中所监听的 props 发生了变化,则会打印对应的值对比,是调试中的神器,极力推荐。

场景4

借助 Chrome Performance 代码进行调试,录制一段操作,在 Timings 选项卡中分析耗时最长逻辑在什么地方,会展现出组件的层级栈,然后精准优化。

场景5

在 React 中是极力推荐函数式编程,可以让数据不可变性作为我们优化的手段。我在  React class 时代大量使用了  immutable.js 结合  redux 来搭建业务,与  React 中  PureComponnet 完美配合,性能保持非常好。但是在  React hooks 中再结合  typescript 它就显得有点格格不入了,类型支持得不是很完美。这里可以尝试一下  immer.js ,引入成本小,写法也简洁了不少。

  1. const nextState = produce(currentState, (draft) => { 
  2.  
  3. draft.p.x.push(2); 
  4.  
  5. }) 
  6.  
  7. // true 
  8.  
  9. currentState === nextState; 

场景6

复杂场景使用 Map 对象代替数组操作, map.get() ,  map.has() ,与数组查找相比尤其高效。

  1. // Map 
  2.  
  3. const map = new Map([['a', { id: 'a' }], ['b', { id: 'b' }], ['c', { id: 'c' }]]); 
  4.  
  5. // 查找值 
  6.  
  7. map.has('a'); 
  8.  
  9. // 获取值 
  10.  
  11. map.get('a'); 
  12.  
  13. // 遍历 
  14.  
  15. map.forEach(n => n); 
  16.  
  17. // 它可以很容易转换为数组 
  18.  
  19. Array.from(map.values()); 
  20.  
  21. // 数组 
  22.  
  23. const list = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]; 
  24.  
  25. // 查找值 
  26.  
  27. list.some(n => n.id === 'a'); 
  28.  
  29. // 获取值 
  30.  
  31. list.find(n => n.id === 'a'); 
  32.  
  33. // 遍历 
  34.  
  35. list.forEach(n => n); 

结语

React 性能调优,除了阻止 rerender ,还有与写代码的方式有关系。最后,我要推一下近期写的  React 状态管理库 https://github.com/MinJieLiu/heo,也可以作为性能优化的一个手段,希望大家从  redux 的繁琐中解放出来,省下的时间用来享受生活。

 

 

责任编辑:张燕妮 来源: 秋风的笔记
相关推荐

2020-08-05 07:27:54

SQL优化分类

2019-01-02 10:49:54

Tomcat内存HotSpot VM

2017-06-12 16:17:07

2020-06-28 16:28:24

Windows 10WindowsU盘

2018-06-13 10:27:04

服务器性能优化

2019-06-27 17:18:02

Java日志编程语言

2021-05-26 05:33:30

5G网络运营商

2018-07-30 11:21:30

华为云

2021-05-21 13:10:17

kill -9微服务Java

2019-12-04 18:45:00

华为Mate X

2019-03-13 10:10:26

React组件前端

2021-09-28 09:00:00

开发JavaScript存储

2021-06-21 09:36:44

微信语音转发

2021-06-07 10:05:56

性能优化Kafka

2021-12-15 07:24:56

SocketTCPUDP

2021-11-25 07:43:56

CIOIT董事会

2020-10-09 10:00:06

Windows 10Windows操作系统

2013-11-28 14:34:30

微软WP

2021-11-10 16:03:42

Pyecharts Python可视化

2021-08-27 14:26:06

开发技能React
点赞
收藏

51CTO技术栈公众号