DEV Community

Discussion on: A Simple Guide to React Context with Hooks

Collapse
jochri3 profile image
Christian Lisangola • Edited

I've defined a default value each time you use createContext but you've not used it even once because anytime your wrap your component with the Provider, you pass it a props value that override whatever value you passed as argument to the createContext function.

Here : const CoolMessageContext = React.createContext('hello hello hello');

The default value is "'hello hello hello'"

And here when you define the Provider <CoolMessageContext.Provider value={'bye bye bye'} /> it's overriden and will never be used.

That's what you've also done when combining context with useState.

You've create the context linke this :

const ObjectContext = React.createContext({
object: {
number: 0,
word: 'hello'
},
setObject: () => {}
});

But the defaultValue is never used anywhere.

It would be good to explain the practical use case of that default value.

In fact it's can be useful when you want to test a component in isolation without wrapping it inside the Provider.It's a very important point to notice because if not, people will create the context everytime with a default even when it's not needed becaus it's not mandatory as said in the official doc : reactjs.org/docs/context.html#reac...

Sorry for my English, it's not my first language🤗