On the React 16 Context doc page, they have examples that look similar to this:
const defaultValue = 'light'; const SomeContext = React.createContext(defaultValue); const startingValue = 'light'; const App = () => ( <SomeContext.Provider theme={startingValue}> Content </SomeContext.Provider> )
It seems that the defaultValue is useless because if you instead set the startingValue
to anything else or don't set it (which is undefined
), it overrides it. That's fine, it should do that.
But then what's the point of the defaultValue
?
If I want to have a static context that doesn't change, it would be nice to be able to just do the below, and just have the Provider pass through the defaultValue
const App = () => ( <SomeContext.Provider> Content </SomeContext.Provider> )
When there's no Provider, the defaultValue argument is used for function createContext. This is helpful for testing components in isolation without wrapping them, or testing it with different values from Provider.
Code sample:
import { createContext, useContext } from "react"; const Context = createContext( "Default Value" ); function Child() { const context = useContext(Context); return <h2>Child1: {context}</h2>; } function Child2() { const context = useContext(Context); return <h2>Child2: {context}</h2>; } function App() { return ( <> <Context.Provider value={ "Initial Value" }> <Child /> {/* Child inside Provider will get "Initial Value" */} </Context.Provider> <Child2 /> {/* Child outside Provider will get "Default Value" */} </> ); }
Codesandbox Demo
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