react icon indicating copy to clipboard operation
react copied to clipboard

Bug: React Context API Not Updating Correctly with Concurrent Mode

Open asimlab opened this issue 2 years ago • 1 comments

Bug Description

I've encountered an issue where the React Context API does not seem to update correctly when used in conjunction with React's Concurrent Mode. The context value appears to become "stuck" at its initial value, failing to update when the provider's value changes.

Steps to Reproduce

  1. Enable Concurrent Mode in a React application.
  2. Create a Context with a dynamic value managed by a state hook.
  3. Consume the context in a component and update the state.
  4. Observe that the context does not update in the consuming component.

Expected Behavior

The expected behavior is for the consuming component to re-render with the new context value when the provider's state changes.

Actual Behavior

The context value in the consuming component does not update after the initial render, even though the provider's state has changed.

Reproducible Demo

[Link to a CodeSandbox or GitHub repo with a minimal reproducible demo of the issue.]

Environment

  • React Version: 17.0.2
  • Browser: Chrome 91.0.4472.124
  • OS: macOS Big Sur 11.4

Additional Context

This issue seems to be related specifically to Concurrent Mode, as disabling Concurrent Mode resolves the problem. It's critical for the correct functioning of context-dependent features in our application.

Thank you for looking into this issue.

asimlab avatar Dec 06 '23 20:12 asimlab

@jo-arciniegas Would be great if you can provide some code example/sandbox to reproduce it. Since for me it works well with the following code:

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

const Context = createContext();

function MyProvider({ children }) {
    const [value, setValue] = useState('Initial Value');

    return (
        <Context.Provider value={{ value, setValue }}>
            {children}
        </Context.Provider>
    );
}

const ChildComponent = () => {
    const { value, setValue } = useContext(Context);

    return (
        <div>
            <h1>Value: {value}</h1>
            <button onClick={() => setValue(Math.random())}>Set a new value</button>
        </div>
    );
};

function App() {
    return (
    <div className="App">
        <MyProvider>
            <ChildComponent />
        </MyProvider>
    </div>
  );
}

export default App;

WOLFRIEND avatar Dec 09 '23 11:12 WOLFRIEND

We have a lot of tests for this so I'm skeptical that this is a bug in React. I'm also not sure what you mean by "disabling concurrent mode" since there is no mode (maybe you mean switching to ReactDOM.render?)

If you can share a sandbox that shows the issue I can re-open and take a look.

rickhanlonii avatar Feb 11 '24 16:02 rickhanlonii