DEV Community

Cover image for ReactJS useContext Hook
Karthick (k)
Karthick (k)

Posted on

ReactJS useContext Hook

The **useContext **hook in React allows components to consume values from the React context. React’s context API is primarily designed to pass data down the component tree without manually passing props at every level. **useContext **is a part of React's hooks system that enables functional components to access context values.

  1. Simplifies accessing shared state across components.
  2. Avoids prop drilling by eliminating the need to pass props down multiple levels.
  3. Works seamlessly with React's Context API to provide global state.
  4. Ideal for managing themes, authentication, or user preferences across the app.
const contextValue = useContext(MyContext);
Enter fullscreen mode Exit fullscreen mode

MyContext: The context object is created using React.createContext().
contextValue: The current context value that we can use in our component.

Creating a Context

Before using useContext, we need to create a context using React.createContext(). This context will provide a value that can be accessed by any child component wrapped in a Context. Provider.

import React, { createContext, useContext, useState } from 'react';

const MyContext = createContext();

function App() {
    const [value, setValue] = useState('Hello, World!');

    return (
        <MyContext.Provider value={value}>
            <ChildComponent />
        </MyContext.Provider>
    );
}

function ChildComponent() {
    const contextValue = useContext(MyContext);
    return <h1>{contextValue}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

createContext() creates a context object (MyContext) that holds a default value.
MyContext.Provider passes down the context value to its child components.
useContext(MyContext) allows components like ChildComponent to access the context value.

Top comments (0)