Runtime-check the re-renderings
To optimize the rendering of React components, we often use the PureRenderMixin
. The PureRenderMixin
mixin only re-renders the components when the props or the state changed according to the shallow equality. This suppose that:
- we use immutable objects (so that the shallow equality always implies the deep equality);
- we rarely create fresh but identical objects (so that the deep equality often implies the shallow equality).
In order to enforce this workflow, we propose some runtime checks to assert that the shallow equality is indeed equivalent to the deep equality over the props. This helped us to remove some useless re-renderings, and protects us against mutation bugs.
Run-time checks
The standard definition of the shouldComponentUpdate
method in pure components is the following:
where shallowEqual
is the shallow equality over an object.
No mutations
We assert that the shallow equality must imply the deep equality. We add the following code in the shouldComponentUpdate
body. This relies on the isEqual
function from lodash.
No useless re-renderings
We assert that the deep equality should imply the shallow equality:
No fresh functions
One last thing, we check that we do not recreate fresh functions for the event handlers in the props. We consider it as a bug since we view it as a performance anti-pattern (see React.js pure render performance anti-pattern):
The code to assert that we do not recreate functions is the following:
Of course, we should not run these checks in production. In our setting with webpack, we wrap these checks into these lines:
Related
On a related note, we also recommend to activate the eslint-plugin-immutable
plugin to syntaxically forbid standard sources of mutations in JavaScript. This plugin would forbid the following lines:
Comments