Today, I am going to show an example of using React Context to understand how it works and the benefits it gives you.
When we develop our apps, we want them to have excellent performance and be maintainable by the development team, which is why React Context emerged.
The problem is that many tutorials and courses only focus on common approaches for application development. It is excellent to consider React Context because it can significantly improve our applications' performance and code maintainability.
Improving Performance and Maintainability with React Context
Here are 3 things you can get about learning and understanding React Context:
- It can prevent unnecessary re-renders
- Significantly improve the performance of our apps
- You will get the mental model required to use any state management with minimal effort
Let's understand it with examples!
Prop drilling approach
Every time the state changes, all components will be rendered, including SlowComponents, hurting performance and causing you to pass many props through various components when SlowComponents don't need those props.
We see 2 problems to solve:
- SlowComponents should not be re-rendered every time the state changes since they do not use it.
- We would have to avoid passing props to SectionOne and SectionTwo to improve the project's maintainability and not pass too many props, worsening the readability of the component and also when there are components inside them that do not use them.
Let's fix it with React Context!
React Context approach
You no longer pass props through all components and get them into the components that use them using the useStateContext custom hook.
When the state changes, the value prop on the StateContext provider will change, and only components that use the useStateContext hook will re-render. The SlowComponents won't re-render anymore!
Conclusion
We have seen a simple way to improve the performance and maintainability of your application in a common use case. This would not be enough for more complex use cases, and we would have to opt for other alternatives, such as state management or refactoring the Context to obtain good performance (create more than one Context, for example). However, it is beneficial to know the essential working as we have seen, to apply it in our applications when needed and take them to the next level.
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 the 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!