close

How to update React Context from inside a child component?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to update React Context from inside a child component? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to update React Context from inside a child component ?

  1. How to update React Context from inside a child component ?

    to update React Context from inside a child component One quite simple solution is to set state on your context by including a setState method in your provider like so:

  2. How to update React Context from inside a child component ?

    to update React Context from inside a child component One quite simple solution is to set state on your context by including a setState method in your provider like so:

Method 1

One quite simple solution is to set state on your context by including a setState method in your provider like so:

return ( 
            <Context.Provider value={{
              state: this.state,
              updateLanguage: (returnVal) => {
                this.setState({
                  language: returnVal
                })
              }
            }}> 
              {this.props.children} 
            </Context.Provider>
        )

And in your consumer, call updateLanguage like so:

// button that sets language config
<Context.Consumer>
{(context) => 
  <button onClick={context.updateLanguage({language})}> 
    Set to {language} // if you have a dynamic val for language
  </button>
<Context.Consumer>

Method 2

I personally like this pattern:

File: context.jsx

import React from 'react';

// The Context 
const TemplateContext = React.createContext({});

// Template Provider
const TemplateProvider = ({children}) => {

    const [myValue, setMyValue] = React.useState(0);

    // Context values passed to consumer
    const value = {
        myValue,    // <------ Expose Value to Consumer
        setMyValue  // <------ Expose Setter to Consumer
    };

    return (
        <TemplateContext.Provider value={value}>
            {children}
        </TemplateContext.Provider>
    )
}

// Template Consumer
const TemplateConsumer = ({children}) => {
    return (
        <TemplateContext.Consumer>
            {(context) => {
                if (context === undefined) {
                    throw new Error('TemplateConsumer must be used within TemplateProvider');
                }
                return children(context)
            }}
        </TemplateContext.Consumer>
    )
}

// useTemplate Hook
const useTemplate = () => {
    const context = React.useContext(TemplateContext);
    if(context === undefined)
        throw new Error('useTemplate must be used within TemplateProvider');
    return context;
}

export {
    TemplateProvider,
    TemplateConsumer,
    useTemplate
}

Then you can create a functional component, if it is a child in the tree of the provider:

File: component.jsx

import React            from 'react';
import {useTemplate}    from 'context.jsx';
const MyComponent = () => {

    // Get the value and setter from the consumer hook
    const {myValue,setMyValue} = useTemplate();

    // Demonstrate incrementing the value
    React.useEffect(()=>{
        let interval = setInterval(()=>{
            setMyValue(prev => prev + 1); // Increment, set in context
        }, 1000) // Every second
        return (
            clearInterval(interval); // Kill interval when unmounted
        )
    },[]) // On mount, no dependencies

    // Render the value as it is pulled from the context
    return (
        <React.Fragment>
            Value of MyValue is: {myValue}
        </React.Fragment>
    )
}

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment