Today we are going to see an exciting trick in React. It consists of a pattern to organise our components to avoid re-rendering them when the parent components are rendered.
You can have serious performance problems If you don't know this pattern.
If you have heavy components and need the state of a parent component to be rendered, you will render all the child components.
That way, you can have slow and poor-performing applications. This pattern will help you to improve application performance.
Children as props pattern. Taking our app to the next level.
Before going into detail with an example, we must be clear about the following 3 concepts:
1. Re-rendering is how React updates components with new data.
2. State update is the initial source of all re-renders.
3. If a component's re-render is triggered, all nested components inside will be re-rendered.
By using this pattern, we will not render the child elements of a component that has had to be rendered. We will improve the performance of the application by avoiding unnecessary processing.
Code examples
Parent component without children prop
First, we are going to see the example without children.
You have this component:
It's a component with a state, a button to change the state and a ChildComponent.
When you click the "Change State" button, React will re-render both ParentComponent and ChildComponent.
Parent component with children prop
Now, wherever you want to have the ParentComponent, you can declare the ChildComponent inside:
When you click the "Change State" button, React only re-renders the ParentComponent.
You avoid the ChildComponent re-render.
Conclusion
You will avoid unnecessary child component re-renders by using this pattern.
That way, you can improve the performance of your applications by using the pattern correctly.
Here, I share a helpful book by Nadia Makarevich that also talks about this topic. I strongly recommend it:
I hope you enjoyed the article.
Join my weekly newsletter, where I share articles to help you become a better front-end developer. You'll receive them directly to your inbox.
If you have any questions, feel free to contact me on LinkedIn, Edi Rodriguez, or leave a comment in the post.
See you in the next post.
Have a great day!
I've been developing in React for six years, but I still pick up new knowledge. This happened today reading this article. Thank you, Edi.