eslint-plugin-react
eslint-plugin-react copied to clipboard
jsx-no-constructed-context-values: class instance false positive
Consider the following code:
const app = new App(); // The 'app' new expression (at line 13) passed as the value prop to the Context provider (at line 22) changes every render. To fix this consider wrapping it in a useMemo hook.eslint[react/jsx-no-constructed-context-values](https://github.com/yannickcr/eslint-plugin-react/tree/master/docs/rules/jsx-no-constructed-context-values.md)
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<AppContext.Provider value={app}>
<AppView />
</AppContext.Provider>
</React.StrictMode>,
);
The rule docs explain:
React Context, and all its child nodes and Consumers are rerendered whenever the value prop changes. Because each Javascript object carries its own identity, things like object expressions ({foo: 'bar'}) or function expressions get a new identity on every run through the component. This makes the context think it has gotten a new object and can cause needless rerenders and unintended consequences.
The rule description only mentions object literals and function expressions and it does not seem to me like React would re-initialize previously initialized class instance on a re-render. `
Since there's no components defined in this code, I wouldn't expect that rule to warn. This seems like an oversight.
@ljharb Could I take on this issue
Go for it!