Say you have the following code:
//App.js
//logoutHandler function defined here
function App {
const testContext = React.createContext({
isLoggedIn: false,
onLogout: logoutHandler
})
return (
<testContext.Provider>
//Some code with components
</testContext.Provider>
)
}
Other than the fact that the values in the value property override the default values, is this any different than setting the value property in testContext like:
//App.js
//logoutHandler function defined here
function App {
return (
<testContext.Provider
value = {{
isLoggedIn: false
onLogout: logoutHandler
}}
>
//Some code with components
</testContext.Provider>
}
Thanks.
Passing value prop through the Provider is useful in many ways:
Providers can be nested to override values deeper within the tree. So, you can have different values for different nodes deeper into the tree.
Consumers that are descendants of a Provider will re-render whenever the value prop of the Provider changes.
You can't do this with the default value. The defaultValue stays the same and doesn't cause re-renders.