Can you explain me why useContext() works for me if I don't wrap my components with Context.Provider? I just exported result of "createContext(someValues)" with predefined values and called useContext(exportedContext) in component and it works. Every tutorial tells me to wrap components. Has something changed in React?
All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes. In other words, If you don't wrap your components with Context.Provider
they won't get re-rendered when the someValues
in createContext(someValues)
changes. You will get the initial value that you set only in the first render.
Demo here
React.Context
always worked this way.
If a component is not wrapped in the Context.Provider
it will receive the default value that was set when the context was created.
Provider's job is to override the default values, essentially providing dependency injection mechanism to React component tree.
Here is a good answer from React team: https://github.com/facebook/react/issues/17912
© 2022 - 2024 — McMap. All rights reserved.
undefined
as a value, I guess it's a compromise between DX and trying to keep the app without crashing in production. – HandymancreateContext()
with no default value, that givesundefined
. – HandymanuseContext
. And where you want them to dynamically change based on certain behaviour, you wrap that subtree in aContext.Provider
that provides newvalue
(overriding the default). Context in React is not just a state management mechanism. It is more of a dependency injection mechanism. If you want it to be a state store, then wrap your tree in a provider and boom now it is a state store. – Albertalberta