Supplementary files for a blog post demonstrating the use of React Memo to mitigate un-required re-rendering.
- Clone this repo to your local machine.
- In a terminal:
cd
into the root of the project directory.npm i
npm start
- In the browser, open the developer console (
F12
). - Play around with the application:
- Clicking on
Update and re-render
will update a value in state that is used by bothNoMemoComponent
andYesMemoComponent
. The values should be updated in each of them, and in the dev console we should see two messages printed out, corresponding to the re-render that both the components undergo. This is expected: both components should re-render because the data they are taking in as props has changed. - Clicking on
Re-render without update
will update a value in state that is NOT used by either of the components. The values within each of them will not change, but if we inspect the console, we see that onlyNoMemoComponent
has printed a message. This is also expected for the following reason:- When we click
Re-render without update
, a value in state updates and the mainApp
is re-rendered due to the state change. - Since
YesMemoComponent
andNoMemoComponent
are both children ofApp
, they should re-render, even if their props have not changed. YesMemoComponent
is wrapped in a memoization, so it does not re-render as the props have not changed.NoMemoComponent
is NOT wrapped in a memoization, so it re-renders since the parentApp
component has re-rendered.
- When we click
- Clicking on
We can carefully employ this memoization strategy in our applications for cases where a component's rendering is expensive. If a component is costly to render, memoization helps to prevent unnecessary re-rendering if the props have not changed.
For more details, do check out the original blog post.