Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access provider value when using useContext hook

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?

like image 372
Orca Prime Avatar asked Oct 31 '18 18:10

Orca Prime


People also ask

How do you use useContext Hooks?

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.

What does the useContext hook return when called?

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.

Can I use useContext in custom hook?

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.


1 Answers

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.

like image 182
Jimi Pajala Avatar answered Nov 21 '22 23:11

Jimi Pajala