import React, { useContext } from 'react'
import { MyContext, MyProvider } from './Context'
const MasterContainer = () =>{
const ctx = useContext(MyContext)
return (
<MyProvider>
{ctx}
<MyContext.Consumer>
{context=><div>{context.age}</div>}
</MyContext.Consumer>
</MyProvider>
)
}
export default MasterContainer
ctx right now is returning undefined when i actually want to pull ctx.age
import React from 'react'
export const MyContext = React.createContext("dude")
export class MyProvider extends React.Component{
state = {
name: 'Hello',
age: 12
}
render(){
return (
<MyContext.Provider value={this.state}>
{this.props.children}
</MyContext.Provider>
)
}
}
Basically i want to access the values of my state in my provider using hooks, how do i go about this?
Syntax: const authContext = useContext(initialValue); The useContext accepts the value provided by React. createContext and then re-render the component whenever its value changes but you can still optimize its performance by using memoization.
The hook returns the value of the context: value = useContext(Context) . The hook also makes sure to re-render the component when the context value changes.
Create the useContext Inside of this custom hook, we'll be using the useContext hook, that allows us to access both the theme and the setTheme function outside of this file. If useContext fails to create a context, it'll return undefined because we forgot the wrap our App or component in a ThemeProvider.
Here is an very simple use case of createContext
-method and updating current context value. CodeSandbox-example
Important to notice here, like described in React.js createContext-method documentation, context value will be matched to the closest matching Provider
above in tree.
React.createContext - Creates an Context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.
Also keep in mind as stated in docs, default value argument is only used if no matching Provider is found.
The defaultValue argument is only used when a component does not have a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them. Note: passing undefined as a Provider value does not cause consuming components to use defaultValue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With