Ayman Morsy
Ayman Morsy

Reputation: 1429

why react-context is returning undefined when no value has been passed from provider, rather than returning a default value?

I have created react context object with a default value like that :

const Mycontext = React.createContext("green");

and expected when no value passed to Proivder

the Consumer will get the defualt value I passesed it but rather than it return undefined

please take a look at this simple example on sandbox and tell me what is my wrong

Upvotes: 2

Views: 1795

Answers (1)

Dennis Martinez
Dennis Martinez

Reputation: 6512

The defaultValue argument is only used when a component does not have a matching Provider above it in the tree.

Found in paragraph 2 here https://reactjs.org/docs/context.html#reactcreatecontext

Since you have a provider, regardless of the provider having a value or not, the context won't use the default. If the context can't find a provider, it'll fallback to the default.

const MyContext = createContext("I'm the default value")

function MyProvider(props) {
  return <MyContext.Provider {...props} />
}

function MyConsumer() {
  return (
    <MyContext.Consumer>{(value) => console.log(value)}</MyContext.Consumer>
  )
}

// Should not use the default from createContext since there is a valid provider.
function AppWithProvider() {
  return (
    <MyProvider>
      <MyConsumer />
    </MyProvider>
  )
}

// Should use the default from createContext since there is no provider.
function AppWithoutProvider() {
  return <MyConsumer />
}

Check it out here https://codesandbox.io/s/condescending-taussig-6n7tq.

Upvotes: 4

Related Questions