Categories
React Answers

How to Update a React Context from Inside a Child Component?

Spread the love

To update a React Context from inside a child component, we can wrap the React Context provider around the child components.

Then we set the value prop of the context provider to the the state setter function that lets us update the context value.

Then we can use the useContext hook to access the context.

For instance, we write:

import React, { useContext, useState } from "react";

const Context = React.createContext();

const Foo = () => {
  const [, setVal] = useContext(Context);

  return (
    <div>
      <button onClick={() => setVal("foo")}>foo</button>
    </div>
  );
};

const Bar = () => {
  const [, setVal] = useContext(Context);

  return (
    <div>
      <button onClick={() => setVal("bar")}>bar</button>
    </div>
  );
};

export default function App() {
  const [val, setVal] = useState();

  return (
    <Context.Provider value={[val, setVal]}>
      <Foo />
      <Bar />
      <p>{val}</p>
    </Context.Provider>
  );
}

to create the Context context with the React.createContext method.

Next, we create the Foo component which calls the useContext hook with Context to return the value of its value prop.

In both Foo and Bar, we call setVal to set the value of val`.

val and setVal are passed down from the array we set as the value of the value prop of Context.Provider.

Since Foo and Bar are inside Context.Provider we can access the context’s value prop value with useContext.

Therefore, when we click the buttons, we see the val value in App change.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *