Yes, you can use useContext
without a Provider
, but the result will be that you receive the default value that was defined when you created the context. Here's a breakdown:
React.createContext(defaultValue)
:
React.createContext()
, you can provide an optional defaultValue
.defaultValue
serves as a fallback value that useContext
will return if no matching Provider
is found in the component tree above the component calling useContext
.useContext(MyContext)
:
useContext(MyContext)
, React searches upwards in the component tree for the nearest MyContext.Provider
.Provider
is found, useContext
returns the value
prop of that Provider
.Provider
is found, useContext
returns the defaultValue
that was passed to React.createContext()
.
Therefore :
useContext
without a surrounding Provider
, you won't get an error. Instead, you'll simply get the default value.Providers
for every test.In essence, the Provider
's role is to override the default context value, and if it is not present, the default value is what is returned.