React Context API

The React Context API allows you to share global state across your component tree without having to pass props down manually at every level. It is especially useful when dealing with deeply nested components or managing data that needs to be accessible throughout an entire app, such as themes, user authentication, or preferences.

1. Creating a Context

To create a context in React, you can use the createContext function. This will give you a Provider and a Consumer component, which are used to pass and consume data.

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

// Create a Context
const MyContext = createContext();

function App() {
    const [state, setState] = useState('Hello, world!');

    return (
        <MyContext.Provider value={{ state, setState }}>
            <Child />
        </MyContext.Provider>
    );
}

function Child() {
    return (
        <MyContext.Consumer>
            {({ state, setState }) => (
                <div>
                    <h2>{state}</h2>
                    <button onClick={() => setState('Hello, React!')}>Change Text</button>
                </div>
            )}
        </MyContext.Consumer>
    );
}

export default App;

In this example, we create a context called MyContext using createContext(). The App component provides the context value, and the Child component consumes the context using the MyContext.Consumer.

2. Using useContext Hook

Instead of using the Consumer component, React provides the useContext hook, which allows you to directly access the context value in a functional component:

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

// Create a Context
const MyContext = createContext();

function App() {
    const [state, setState] = useState('Hello, world!');

    return (
        <MyContext.Provider value={{ state, setState }}>
            <Child />
        </MyContext.Provider>
    );
}

function Child() {
    const { state, setState } = useContext(MyContext);

    return (
        <div>
            <h2>{state}</h2>
            <button onClick={() => setState('Hello, React!')}>Change Text</button>
        </div>
    );
}

export default App;

In this updated example, we replace the MyContext.Consumer with the useContext hook. This allows the Child component to consume the context value directly.

3. Updating Context Values

You can update context values from any component within the context provider. Here's an example where the state is updated through the setState function:

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

// Create a Context
const MyContext = createContext();

function App() {
    const [state, setState] = useState('Hello, world!');

    return (
        <MyContext.Provider value={{ state, setState }}>
            <Child />
            <AnotherChild />
        </MyContext.Provider>
    );
}

function Child() {
    const { state, setState } = useContext(MyContext);

    return (
        <div>
            <h2>{state}</h2>
            <button onClick={() => setState('Changed from Child!')}>Change Text</button>
        </div>
    );
}

function AnotherChild() {
    const { state } = useContext(MyContext);

    return <h2>{state}</h2>;
}

export default App;

In this example, the setState function is used in one component (Child) to update the global state, and this update is automatically reflected in other components (AnotherChild) that consume the context.

4. Default Context Values

You can provide default values to the context to avoid undefined values if the context is consumed without a provider:

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

// Create a Context with default values
const MyContext = createContext({ state: 'Default State', setState: () => {} });

function App() {
    const [state, setState] = useState('Hello, world!');

    return (
        <MyContext.Provider value={{ state, setState }}>
            <Child />
        </MyContext.Provider>
    );
}

function Child() {
    const { state, setState } = useContext(MyContext);

    return (
        <div>
            <h2>{state}</h2>
            <button onClick={() => setState('Changed from Child!')}>Change Text</button>
        </div>
    );
}

export default App;

Here, we provide a default value to the context using createContext, which ensures that the context has a fallback value if no Provider is found.

5. Summary

The React Context API provides a way to share state across your component tree without needing to pass props manually. It helps avoid prop drilling and makes managing global state in your React application much easier. You can use createContext to create a context, and useContext or Consumer to consume the context in your components. Context can also be updated and passed down the component tree.

0 Interaction
203 Views
Views
41 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home