Categories
React Answers

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

Spread the love

Sometimes, we want to update a React Context from inside a child component.

In this article, we’ll look at how to update a React Context from inside a child component.

Update a React Context from Inside a Child Component

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.

Conclusion

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.