-
Notifications
You must be signed in to change notification settings - Fork 50.2k
Description
Since React 19, nested providers for the same context will lead to unnecessary render calls for some scenarios. I wrote a unit test and confirmed that React 18.3.1 behaves as expected.
E.g. for the following pseudo-code React component structure:
<SomeContextProvider>
<SomeContextConsumer>
<SomeContextProvider>
<SomeContextConsumer />
</SomeContextProvider>
</SomeContextConsumer>
</SomeContextProvider>If the value provided by the outer SomeContextProvider changes, the innermost SomeContextConsumer will also be rendered. (Actually it will only "semi-render", because even though the function is called, the result is ignored.)
It is probably only an unnecessary detail for most users, but for me it broke some tests which track every single render for performance reasons and it actually causes >1k unnecessary component function calls in some situations because I utilize some nested contexts for some widely used information where it is important that elements are only rerendered when the context value changes. So if the top-level context provider is updated, but another provider between the element and it is not updated, the element should not be rendered.
Also, it is very concerning that it executes the component function but ignores the result.
React version: 19.2.3 (and 19.0.0)
Works in 18.3.1
Steps To Reproduce
- Open code example below. Execute
vitestin terminal.
- The test will fail, because the component was kind of rendered, even though it was unnecessary.
- Downgrade to React 18.3.1 by updating package.json and running
npm install - Execute
vitestin terminal. The test will pass.
Link to code example:
Repro code in unit test on Stackblitz
The current behavior
The inner component consuming the React context is called, even though the context value has not changed for it.
The expected behavior
Like in React 18.3.1: Only component functions where the context value has changed will be called.