Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.createContext point of defaultValue?

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> ) 
like image 461
Merlin -they-them- Avatar asked Apr 20 '18 20:04

Merlin -they-them-


1 Answers

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

like image 164
Arielle Nguyen Avatar answered Oct 13 '22 08:10

Arielle Nguyen