Don't overoptimize your React App
varunprashar5
Posted on August 24, 2021
๐ข๐ฝ๐๐ถ๐บ๐ถ๐๐ถ๐ป๐ด ๐๐ผ๐๐ฟ ๐ฅ๐ฒ๐ฎ๐ฐ๐ ๐๐ฝ๐ฝ
Do checkout the video for more details:
If you have a parent-child component structure then Whenever the parent state changes it will re-render.
Do you know it will even re-render your child? No matter if your child uses any prop or not it will still re-render.
Ideally, Child should re-render only if: parent prop or method used inside the child is changed.
๐๐ผ๐ ๐๐ผ ๐ฝ๐ฟ๐ฒ๐๐ฒ๐ป๐ ๐๐ป๐ป๐ฒ๐ฐ๐ฒ๐๐๐ฎ๐ฟ๐ ๐ฟ๐ฒ-๐ฟ๐ฒ๐ป๐ฑ๐ฒ๐ฟ๐ ?
The solution is "๐ฅ๐ฒ๐ฎ๐ฐ๐.๐บ๐ฒ๐บ๐ผ"
React.memo (is a higher-order component) takes the component and memoizes the rendered output of the wrapped component.
So whenever there is a re-render in the parent, For a child it will compare the props and if all the props are the same it reuses the memoized result skipping the next rendering.
๐ข๐ฏ๐๐ฒ๐ฟ๐๐ฎ๐๐ถ๐ผ๐ป:
- Pressing the "click" button, updates the state due to which re-renders
- is re-rendered every time "Parent" is re-rendered (even it is not using any parent state)
- is not re-rendered when "Parent" is re-rendered (As it is using memoised result)
๐๐บ๐ฝ๐ผ๐ฟ๐๐ฎ๐ป๐ ๐ฝ๐ผ๐ถ๐ป๐๐:
If you are using function as a prop in your child, it will still re-render even if props are the same in comparison (let's discuss it in the next post)
If you are thinking to have every component to use React.memo then it may overkill the performance in some scenarios where it will first compare the props if they are not the same it will still do the re-rendering (extra comparison check)
Do check the profiler to actually figure out if it will be worth using it
If a child is re-rendering it doesn't mean it is costly unless it is doing the "commit" phase which actually does the real DOM changes.
Before preventing re-renders, Do fix your SLOW renders.
Do share your thoughts in the comments
Posted on August 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 18, 2024