Skip to content Skip to sidebar Skip to footer

React Optimization Of Stateless, Functional Components Through Shouldcomponentupdate

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. If I'm building

Solution 1:

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.

Post a Comment for "React Optimization Of Stateless, Functional Components Through Shouldcomponentupdate"