React Hooks记住成本

问题描述 投票:0回答:1

React.useMemo()是否有成本比较,如shouldComponentUpdate()中的React.PureComponent

将变量经常更改为useMemo()useCallback()的deps是不是很糟糕。

谢谢

reactjs react-hooks
1个回答
1
投票

这是一个μ基准,React.memo()似乎是最快的,PureComponent在中间,useCallback()一直是最慢的:

class P extends React.PureComponent {
  render() {
    return <span onClick={() => this.props.n} />
  }
}
function C(props) {
  const c = React.useCallback(() => props.n, [props.n])
  return <span onClick={c} />
}
const M = React.memo(props => <span onClick={() => props.n} />)

const target = document.getElementById('target')
function test(o) {
  console.log('From fastest to slowest:')
  const entries = Object.entries(o)
  const results = new Map(entries.map(([name]) => [name, 0]))
  for (let i = 0; i < 1e3; i++) {
    for (let [name, X] of entries) {
      const start = performance.now()
      for (let j = 0; j < 1e2; j++) {
        ReactDOM.render(<X n={i} />, target)
      }
      const took = performance.now() - start
      results.set(name, results.get(name) + took)
    }
  }
  const sorted = Array.from(results).sort(([, a], [, b]) => a-b)
  for (let [name, t] of sorted) {
    console.log(name, t)
  }
}

test({PureComponent: P, useCallback: C, memo: M})
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
<div id="target" hidden></div>
© www.soinside.com 2019 - 2024. All rights reserved.