[SOLVED] How to update React Context from inside a child component?

Issue

This Content is from Stack Overflow. Question asked by HuLu ViCa

I’m using the second answer of this post to implement a React context that can be updated from a child component. This is my code so far:

app/authContext/index.tsx

import React, { useState } from "react";

export const AuthContext = React.createContext({
  auth: {user: null},
  setAuth: () => {}
})

export const AuthContextProvider = (props: any) => {

  const setAuth= (auth: any) => {
    setState({...state, auth: auth})
  }

  const initState = {
    auth: {user: null},
    setAuth: setAuth
  } 

  const [state, setState] = useState(initState)

  return (
    <AuthContext.Provider value={state}>
      {props.children}
    </AuthContext.Provider>
  )
}

app/index.tsx

import React, { useState } from 'react';
import { ThemeProvider } from '@mui/material/styles';
import { Routes, Route } from "react-router-dom";

import './App.css';
import {mayan} from "./themes/mayan";
import AppHeader from './appHeader';

import { AuthContextProvider } from "./authContext";

import Home from "./Routes/home";
import Login from "./Routes/login";

function App() {
  return (
    <ThemeProvider theme={mayan}>
      <AuthContextProvider>
        <div className="App">
          <AppHeader />
          <header className="App-body">
            <Routes>
              <Route path="/" element={<Home />} />
              <Route path="login" element={<Login />} />
            </Routes>
          </header>
        </div>
      </AuthContextProvider>
    </ThemeProvider>
  );
}

export default App;

The problem is that I’m getting this error:

TS2322: Type '{ auth: { user: null; }; setAuth: (auth: any) => void; }' is not assignable to type '{ auth: { user: null; }; setAuth: () => void; }'.
  Types of property 'setAuth' are incompatible.
    Type '(auth: any) => void' is not assignable to type '() => void'.
    20 |
    21 |   return (
  > 22 |     <AuthContext.Provider value={state}>
       |                           ^^^^^
    23 |       {props.children}
    24 |     </AuthContext.Provider>
    25 |   )

I suppose this error raises because I’m using TypeScript instead of JavaScript, but I can’t find how to solve it.



Solution

Using hooks

Hooks were introduced in 16.8.0 so the following code requires a minimum version of 16.8.0 (scroll down for the class components example). CodeSandbox Demo

1. Setting parent state for dynamic context

Firstly, in order to have a dynamic context which can be passed to the consumers, I’ll use the parent’s state. This ensures that I’ve a single source of truth going forth. For example, my parent App will look like this:

const App = () => {
  const [language, setLanguage] = useState("en");
  const value = { language, setLanguage };

  return (
    ...
  );
};

The language is stored in the state. We will pass both language and the setter function setLanguage via context later.

2. Creating a context

Next, I created a language context like this:

// set the defaults
const LanguageContext = React.createContext({
  language: "en",
  setLanguage: () => {}
});

Here I’m setting the defaults for language (‘en’) and a setLanguage function which will be sent by the context provider to the consumer(s). These are only defaults and I’ll provide their values when using the provider component in the parent App.

Note: the LanguageContext remains same whether you use hooks or class based components.

3. Creating a context consumer

In order to have the language switcher set the language, it should have the access to the language setter function via context. It can look something like this:

const LanguageSwitcher = () => {
  const { language, setLanguage } = useContext(LanguageContext);
  return (
    <button onClick={() => setLanguage("jp")}>
      Switch Language (Current: {language})
    </button>
  );
};

Here I’m just setting the language to ‘jp’ but you may have your own logic to set languages for this.

4. Wrapping the consumer in a provider

Now I’ll render my language switcher component in a LanguageContext.Provider and pass in the values which have to be sent via context to any level deeper. Here’s how my parent App look like:

const App = () => {
  const [language, setLanguage] = useState("en");
  const value = { language, setLanguage };

  return (
    <LanguageContext.Provider value={value}>
      <h2>Current Language: {language}</h2>
      <p>Click button to change to jp</p>
      <div>
        {/* Can be nested */}
        <LanguageSwitcher />
      </div>
    </LanguageContext.Provider>
  );
};

Now, whenever the language switcher is clicked it updates the context dynamically.

CodeSandbox Demo

Using class components

The latest context API was introduced in React 16.3 which provides a great way of having a dynamic context. The following code requires a minimum version of 16.3.0. CodeSandbox Demo

1. Setting parent state for dynamic context

Firstly, in order to have a dynamic context which can be passed to the consumers, I’ll use the parent’s state. This ensures that I’ve a single source of truth going forth. For example, my parent App will look like this:

class App extends Component {
  setLanguage = language => {
    this.setState({ language });
  };

  state = {
    language: "en",
    setLanguage: this.setLanguage
  };

  ...
}

The language is stored in the state along with a language setter method, which you may keep outside the state tree.

2. Creating a context

Next, I created a language context like this:

// set the defaults
const LanguageContext = React.createContext({
  language: "en",
  setLanguage: () => {}
});

Here I’m setting the defaults for language (‘en’) and a setLanguage function which will be sent by the context provider to the consumer(s). These are only defaults and I’ll provide their values when using the provider component in the parent App.

3. Creating a context consumer

In order to have the language switcher set the language, it should have the access to the language setter function via context. It can look something like this:

class LanguageSwitcher extends Component {
  render() {
    return (
      <LanguageContext.Consumer>
        {({ language, setLanguage }) => (
          <button onClick={() => setLanguage("jp")}>
            Switch Language (Current: {language})
          </button>
        )}
      </LanguageContext.Consumer>
    );
  }
}

Here I’m just setting the language to ‘jp’ but you may have your own logic to set languages for this.

4. Wrapping the consumer in a provider

Now I’ll render my language switcher component in a LanguageContext.Provider and pass in the values which have to be sent via context to any level deeper. Here’s how my parent App look like:

class App extends Component {
  setLanguage = language => {
    this.setState({ language });
  };

  state = {
    language: "en",
    setLanguage: this.setLanguage
  };

  render() {
    return (
      <LanguageContext.Provider value={this.state}>
        <h2>Current Language: {this.state.language}</h2>
        <p>Click button to change to jp</p>
        <div>
          {/* Can be nested */}
          <LanguageSwitcher />
        </div>
      </LanguageContext.Provider>
    );
  }
}

Now, whenever the language switcher is clicked it updates the context dynamically.

CodeSandbox Demo


This Question was asked in StackOverflow by mshameer and Answered by Divyanshu Maithani It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?