Memoising components

DEMO
without memoisation
0 lights on
with memoisation
0 lights on

By default, if a parent rerenders, all of its children will also rerender. By memoising each dot light, it will only rerender if its props change.

Note that we have to wrap the parent's toggle function using theuseCallback hook. Otherwise, the anonymous function will always get a new reference on each render, and will then be considered as a changed prop that's passed to the child.

You can learn about this in more detail inAlex Sidorenko's blog post.

This perfomance optimisation doesn't always need to be applied. Only use it for very long lists or when the children components are expensive to rerender.
MemoisingComponentsDemo.jsx

LightGrid.jsx
DotLight.jsx
const MemoisingComponents = () => {
  return (
    <Wrapper>
      <LightGridDemo isMemoised={false} />
      <LightGridDemo isMemoised={true} />
    </Wrapper>
  );
};

Note: Code snippets do not include styling details unless they are the focus of the exercise.

Copyright © 2022 Explore React