React Context has been around for a while now, and it’s a great tool to share data between components. However, it’s not the best tool for performance. But for smaller applications, they still can benefit from the Context mental model.
Utilizing Context or similar state management libraries enables the direct passage of data between components deep in the render tree, bypassing the need to thread it through props. This approach can enhance app performance by averting the re-rendering of intermediary components.
Nevertheless, caution is warranted with Context, as any change in the Context provider’s value triggers a re-render for all associated components. Standard memoization techniques are ineffective in preventing this re-render. To mitigate Context re-renders, it is advisable to consistently memoize the values passed to the provider.
Further minimizing re-renders can be achieved by segmenting the Context provider into multiple providers. Transitioning from useState to useReducer can also contribute to this optimization.
Despite the absence of dedicated selectors for Context, emulating their functionality is possible through higher-order components and React.memo.
Personally, I don’t use Context that much, I used it in a couple learning projects. I prefer to use Redux or Zustand for state management. But I think it’s a good tool to know, and it’s good to know its limitations.
If you have any suggestions or questions, feel free to reach out to me on Twitter or LinkedIn.
P.S. this post is inspired by the book, but it’s not a summary of it. I’m just sharing what I learned from it. If you want to learn more about React, I highly recommend you to read it.