shouldComponentUpdate in function components
I have a question regarding React's shouldComponentUpdate
(when not overwritten). I do prefer pure, function components, but I am afraid that it updates every time, even though props/state did not change. So I am considering using the PureComponent class instead.
My question regarding that: Do function components have the same shouldComponentUpdate
check as PureComponents? Or does it update every time?
In React, functional components are stateless and they do not have lifecycle methods. Stateless components are an elegant way of writing React components without much code in our bundle. But internally, Stateless components are wrapped in a class without any optimizations currently applied. That means both stateless and stateful components has the same code path internally (although we define them differently).
But in the future React may optimize stateless components as said it here:
In the future, we'll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations. [ More reading... ]
shouldComponentUpdate
This is where you we can apply our custom optimizations and avoid unnecessary re-rendering of components. The usage of this method with different types of components are explained below:
Functional Stateless components
As said before, stateless components do not have life cycle methods thus we cannot optimize them using shouldComponentUpdate
. But they are already optimized in a different way, they have much simpler and elegant code structure and costs less bytes than a component with all life-cycle hooks.
extend React.PureComponent
From React v15.3.0 , we have a new base class called PureComponent
to extend with PureRenderMixin
built-in. Under the hood this employs a shallow comparison of current props/state with next props/state within a shouldComponentUpdate
.
That said, we still cannot rely on PureComponent
class to get our components optimized to the level we want. This anomaly case happens if we have props with Object
types (arrays, dates, plain objects). This is because we have this problem when comparing objects:
const obj1 = { id: 1 };
const obj2 = { id: 1 };
console.log(obj1 === obj2); // prints false
Hence a shallow comparison won't suffice to determine whether things have changed or not. But use PureComponent
class if your props are just string, number, boolean.. and not objects. Also use it if you do not want to implement your own custom optimizations.
extend React.Component
Consider the above example; if we know that the objects have changed if the id
has changed, then we can implement our own custom optimization by comparing obj1.id === obj2.id
. That is where we can extend
our normal Component
base class and use shouldComponentUpdate
to do the comparison of specific keys by ourselves.
上一篇: 声明朋友功能
下一篇: 应该在函数组件中更新组件