Search code examples
javascriptreactjsjsxreact-context

React: Why isn't my context value updated?


I'm playing with React Context API. I created a simple component:

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

const MyContext = createContext(1);

const MyComponent = () => (
    <>
        <p>{useContext(MyContext)}</p>
        <MyContext.Provider value={2}>
            <p>{useContext(MyContext)}</p>
        </MyContext.Provider>
    </>
);

export default MyComponent;

I'm getting two <p>1</p>. Why isn't the second context updated with 2? Am I using useContext() incorrectly?


Solution

  • You must use a separate Component to get Context to work.

    I've filed a bug about this; see https://github.com/facebook/react/issues/18629

    Simply split the code using the Context into a different Component.

    const Inner = () => (
        <p>{useContext(MyContext)}</p>
    );
    
    const MyComponent = () => (
        <>
            <p>{useContext(MyContext)}</p>
            <MyContext.Provider value={2}>
                <Inner />
            </MyContext.Provider>
        </>
    );
    

    That should fix it.