React Hooks记住成本

时间:2019-04-27 00:59:23

标签: reactjs react-hooks

React.useMemo()是否具有比较费用,就像shouldComponentUpdate()中的React.PureComponent一样?

将经常更改的变量放入useMemo()useCallback()的部门很不好。

谢谢

1 个答案:

答案 0 :(得分: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>