DEV Community

Cover image for Understanding and Using the useContext Hook in React
Abdulrahman Gaoba
Abdulrahman Gaoba

Posted on

Understanding and Using the useContext Hook in React

The useContexthook in React allows a component to access data from a context object without having to pass props down through multiple levels of the component tree. This can make the component structure of a React application more efficient and easier to understand.

To use the useContexthook, a context object must first be created using the createContext function. This function takes an initial value as an argument, which will be the value of the context when it is first accessed by a component.

import React, { createContext } from 'react';

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

Once the context object has been created, it can be provided to a component tree using the Providercomponent. This component takes a value prop, which is the current valueof the context.

import { MyContext } from './MyContext';

function App() {
  return (
    <MyContext.Provider value={someValue}>
      {/* component tree */}
    </MyContext.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode

Any component that is a child of the Providercomponent can access the context value using the useContexthook. The hook takes the context object as an argument and returns the current value of the context.

import { MyContext } from './MyContext';

function ChildComponent() {
  const contextValue = useContext(MyContext);

  return <div>{contextValue}</div>;
}
Enter fullscreen mode Exit fullscreen mode

The useContexthook also allows a component to update the context value by providing a new value to the Providercomponent. When the context value is updated, all components that are using the context will re-render with the new value.

import { MyContext } from './MyContext';

function App() {
  const [contextValue, setContextValue] = useState({});

  return (
    <MyContext.Provider value={contextValue}>
      <button onClick={() => setContextValue({ ...contextValue, newProp: 'newValue' })}>
        Update Context
      </button>
      <ChildComponent />
    </MyContext.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode

In summary, the useContexthook in React allows components to access and update data from a context object without having to pass props down through multiple levels of the component tree. This can make the component structure of a React application more efficient and easier to understand.

Top comments (0)