DEV Community

Glenn all
Glenn all

Posted on

3 2

how to use react context?

React's Context API allows you to share values such as state or data between components without passing props down manually through every level of the component tree. This can be especially useful when you have some values that are needed by many components in your application.

To use the Context API, you first need to create a context using the createContext() method from the react package. This method returns an object with two components: Provider and Consumer.

import { createContext } from 'react';

const MyContext = createContext();
Enter fullscreen mode Exit fullscreen mode

The Provider component is used to provide a value for the context, which can then be consumed by the Consumer component. The Provider component should be placed at the root of your component tree, wrapping the components that need access to the context value.

import MyContext from './MyContext';

function App() {
  return (
    <MyContext.Provider value="Hello World">
      <MyComponent />
    </MyContext.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode

In the example above, the value "Hello World" is provided for the MyContext context. This value can then be consumed by the MyComponent component, or any other component nested inside it, using the Consumer component.

import MyContext from './MyContext';

function MyComponent() {
  return (
    <MyContext.Consumer>
      {value => <p>{value}</p>}
    </MyContext.Consumer>
  );
}```



The Consumer component expects a function as its child, which will be called with the current context value. The function should return a React element that uses the context value. In the example above, the context value is used to render a p element with the value inside it.

You can also use the useContext() hook from the react package to consume the context value inside a functional component.



```js
import { useContext } from 'react';
import MyContext from './MyContext';

function MyComponent() {
  const value = useContext(MyContext);
  return <p>{value}</p>;
}
Enter fullscreen mode Exit fullscreen mode

The useContext() hook takes the context object as its argument and returns the current context value. You can then use this value inside the component.

It's also possible to update the context value using the useState() hook inside a component that is a descendant of the Provider component. This can be useful for implementing state management using the Context API.

import { useContext, useState } from 'react';
import MyContext from './MyContext';

function MyComponent() {
  const [value, setValue] = useState(useContext(MyContext));

  function handleClick() {
    setValue('Hello World!');
  }

  return (
    <>
      <p>{value}</p>
      <button onClick={handleClick}>Update Value</button>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

In the example above, the context value is initially set to the value provided by the Provider component using the useContext() hook. A button element is then rendered with an onClick event handler that updates the value using the setValue() function from the useState() hook

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ā¤ļø