React optimization of stateless, functional components through shouldComponentUpdate

前端 未结 1 2063
闹比i
闹比i 2021-02-14 13:33

I know that a key point of optimization for React is by using shouldComponentUpdate() lifecycle hook to check the current state/props against the next/state props.<

相关标签:
1条回答
  • 2021-02-14 14:10

    Stateless components are candidates for optimization in the future and the docs hint at it without going into details:

    In an ideal world, most of your components would be stateless functions because in the future we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations. This is the recommended pattern, when possible.

    Source


    Currently however, stateless components do not optimize performance by skipping the render process if the props are unchanged. This has been confirmed by a member of the react team:

    For complex components, defining shouldComponentUpdate (eg. pure render) will generally exceed the performance benefits of stateless components. The sentences in the docs are hinting at some future optimizations that we have planned, whereby we won't allocate an internal instance for stateless functional components (we will just call the function). We also might not keep holding the props, etc. Tiny optimizations. We don't talk about the details in the docs because the optimizations aren't actually implemented yet (stateless components open the doors to these optimizations).

    [...]

    There are discussions about having a pureRender flag that you could set on the function, or allowing it to participate in the shouldUpdate lifecycle, but that's currently not implemented. At the moment, stateless functions can not be pure-render.

    It is worth keeping in mind that sometimes people abuse/overuse pure-render; it can sometimes be as or more expensive than running the render again, because you're iterating over the array of props and potentially doing things like string compares, which is just extra work for components that ultimately return true and then proceed to rerender anyway. PureRender / shouldComponentUpdate really is considered an escape hatch for performance and is not necessarily something that should be blindly applied to every component.

    Source


    My takeaway from this discussion is that in certain cases for complex components, the performance can be increased by implementing shouldComponentUpdate in comparison to stateless components. On the other hand, I would strongly consider whether the performance benefits are significant enough to outweigh the added complexity and bigger footprint of the component.

    0 讨论(0)
提交回复
热议问题