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.
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