After reading the official documentation about context (https://reactjs.org/docs/context.html), I have a feeling its use should mostly be limited to the situations when we have some variables we could consider "global" that we must send to many components on different nesting levels (like current theme, locale, currently authenticated user).
Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.
and
Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult.
I would like to use Context to facilitate communication between components that are far from each other in the component tree. Many users used Redux for that (though it's not its main purpose), which was not similarly discouraged, even though when used with React (through react-redux package) such an approach is internally powered by Context.
Is there any disadvantage that Context has compared to redux + react-redux (barring the fact that Redux has a different way to update state) that should make me not use Context in the described scenario? The docs say it makes component reuse more difficult. How does it do it, and isn't this con also relevant to redux + react-redux duo?
It is not discouraged and can be used for component communication at different levels of nesting.
Is there any disadvantage that Context has compared to redux + react-redux (barring the fact that Redux has a different way to update state) that should make me not use Context in the described scenario? The docs say it makes component reuse more difficult.
React context can be less convenient to debug because it currently cannot make use of Redux devtools. There's an issue that can be watched, yet any possible solution can't cover interactions through context API that are performed with callback functions, e.g. this modal example, while dispatched Redux actions can be tracked.
The documentation doesn't explain why it is difficult to reuse, and 'difficult' is subjective. A component that relies on the context imposes hidden dependency on respective Provider in component hierarchy. It is loosely coupled to it yet it may malfunction if there's no expected provided value; if there's no Provider, Consumer is still rendered with undefined value, this behaviour cannot be changed without manual value validation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With