Why does react context needs a provider?

Viewed 226

Context state can just be an observable and update components who subscribe like the observer pattern.

If you need the context state in a component just subscribe to a specific context.

Why do we need to render the context provider at the root of the app in order to use it somewhere else?

I ask since i see many libraries and apps use context now as the main way to share state between components but I don't understand the need to render the provider at the root of the app since each shared state (context) could be initialized outside of render functions

I made an npm package that does something similar in order to simplify the context/shared states of an app as an example of what i mean

https://www.npmjs.com/package/jstates And a package for react bindings https://www.npmjs.com/package/jstates-react

2 Answers

The reason is IMHO is recat tries to follow a paradigm where you don't have global state. In general you want state to be as local as possible. This allows better testing where you can feed mock state into the provider easily.

If you have a global object where everyone subscribe to it would be unclear where state is coming from. With the context provider it very clear and state is encapsulated inside the component tree (no global objects).

Context API has to support multiple instances of the same context provider (e.g. while migrating part of the project to a new version of some library).

Even if libraries that use Context are most often used as singletons (for managing global state), when Thinking in React, authors need to support composable Components, not just global singletons. React API design also prefers Components over other patterns when feasible (e.g. <Suspense /> and <Provider />, but not life cycle hooks).

When designing support of multiple instances, some pattern for inversion of control is advisable for easier debugging (more constrains == less things that could go wrong).

Thus, explicit visibility in the React Components tree is preferred (notice that even life cycle methods and hooks are visible in the tree node details - but you only need to see those for a single node, not to identify "all children that have access to this context").

Related