eslint-plugin-react icon indicating copy to clipboard operation
eslint-plugin-react copied to clipboard

jsx-no-constructed-context-values: class instance false positive

Open mckravchyk opened this issue 2 years ago • 3 comments

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. `

mckravchyk avatar May 23 '22 11:05 mckravchyk

Since there's no components defined in this code, I wouldn't expect that rule to warn. This seems like an oversight.

ljharb avatar May 23 '22 17:05 ljharb

@ljharb Could I take on this issue

greatsage-raphael avatar Jun 20 '22 15:06 greatsage-raphael

Go for it!

ljharb avatar Jun 21 '22 04:06 ljharb