Performance penalty of creating handlers on every render with react-hooks

前端 未结 5 2138
野的像风
野的像风 2020-12-03 16:54

I\'m currently very amazed about the use cases of the new react hooks API and what you can possibly do with it.

A question that came up while experimenting was how e

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 17:36

    The React FAQs provide an explanation to it

    Are Hooks slow because of creating functions in render?

    No. In modern browsers, the raw performance of closures compared to classes doesn’t differ significantly except in extreme scenarios.

    In addition, consider that the design of Hooks is more efficient in a couple ways:

    Hooks avoid a lot of the overhead that classes require, like the cost of creating class instances and binding event handlers in the constructor.

    Idiomatic code using Hooks doesn’t need the deep component tree nesting that is prevalent in codebases that use higher-order components, render props, and context. With smaller component trees, React has less work to do.

    Traditionally, performance concerns around inline functions in React have been related to how passing new callbacks on each render breaks shouldComponentUpdate optimizations in child components. Hooks approach this problem from three sides.

    So overall benefits that hooks provide are much greater than the penalty of creating new functions

    Moreover for functional components, you can optimize by making use of useMemo so that the components are re-rendering when there is not change in their props.

提交回复
热议问题