Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  139] [ 3]  / answers: 1 / hits: 71955  / 6 Years ago, fri, april 20, 2018, 12:00:00

On the React 16 Context doc page, they have examples that look similar to this one:


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 do something like below, and just have the Provider been passed through the defaultValue


const App = () => (
<SomeContext.Provider>
Content
</SomeContext.Provider>
)

More From » reactjs

 Answers
9

When there's no Provider, the defaultValue argument is used for the function createContext. This is helpful for testing components in isolation without wrapping them, or testing it with different values from the 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


[#54604] Wednesday, April 18, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kinsley

Total Points: 352
Total Questions: 84
Total Answers: 94

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;