jay philip camillo
jay philip camillo

Reputation: 65

Why is useContext() not returning the Provider value instead returning the initial value?

import React, { useContext, createContext } from "react";

const messageContext = createContext("Hello");

const Context = () => {

    const message = useContext(messageContext);

    return (
        <messageContext.Provider value="Hi">

            <div style={{ marginTop: 1000 }}>{message}</div> 
            {/* Result: Hello */}

            <messageContext.Consumer>
                {message => {
                    return <div style={{ marginTop: 1000 }}>{message}</div>;
                }}
            </messageContext.Consumer>
            {/* Result: Hi */}

        </messageContext.Provider>
    );
};
export { Context };

I want to use the useContext() hook but it always returns the initial value which is "Hello".

Using <messageContext.Consumer> has no problem. It returns "Hi" but i want to use the useContext hook.

Upvotes: 2

Views: 858

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85151

When you grab something from context, you get it from the nearest provider up the component tree. Since you called useContext inside the Context component, it will look for a provider higher up the tree than Context. None exists, so you get the default value instead. Your example with the messageContext.Consumer is inside a provider, so it can see that value.

There's little reason to consume a value in the exact same component where you provide it. In order to provide the value you presumably have some logic which results in a local variable, and you can reuse that same local variable for any other parts of the component that need it.

Upvotes: 3

Related Questions