Categories
React Answers

How to Change Context Value While Using the useContext React Hook?

Spread the love

Sometimes, we want to change context value while using the useContext React hook.

In this article, we’ll look at how to change context value while using the useContext React hook.

Change Context Value While Using the useContext React Hook

We can pass in the state change function to the context to let us call them anywhere.

This way, we can change the value in whatever component that receives the context.

For example, we can write:

const { createContext, useContext, useState } = React;

const ThemeContext = createContext({});

function Content() {
  const { style, color, toggleStyle, changeColor } = useContext(
    ThemeContext
  );

  return (
    <div>
      <p>
        {color} {style}
      </p>
      <button onClick={toggleStyle}>Change style</button>
      <button onClick={() => changeColor('green')}>Change color</button>
    </div>
  );
}

function App() {
  const [style, setStyle] = useState("light");
  const [color, setColor] = useState(true);

  function toggleStyle() {
    setStyle(style => (style === "light" ? "dark" : "light"));
  }

  function changeColor(color) {
    setColor(color);
  }

  return (
    <ThemeContext.Provider
      value={{ style, visible, toggleStyle, changeColor }}
    >
      <Content />
    </ThemeContext.Provider>
  );
}

We created the ThemeContext , which we use in the App component to get the provider and wrap that around the Content component.

Then we pass our state change functions with the state variables into the context by passing them into the object in the value prop.

Then in the Content component, we can call the toggleStyle and toggleStyle and changeColor functions to change the states in App .

We get those functions in Content with the useContext hook.

Conclusion

We can pass in the state change function to the context to let us call them anywhere.

This way, we can change the value in whatever component that receives the context.

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 *