Skip to content

[Fix] jsx-no-constructed-context-values: detect constructed context values in React 19 <Context> usage #3910

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

# Change Log

All notable changes to this project will be documented in this file.
Expand All @@ -10,11 +9,13 @@ This change log adheres to standards from [Keep a CHANGELOG](https://keepachange
### Fixed
* [`no-unknown-property`]: allow shadow root attrs on `<template>` ([#3912][] @ljharb)
* [`prop-types`]: support `ComponentPropsWithRef` from a namespace import ([#3651][] @corydeppen)
* [`jsx-no-constructed-context-values`]: detect constructed context values in React 19 `<Context>` usage ([#3910][] @TildaDares)

### Changed
* [Docs] [`button-has-type`]: clean up phrasing ([#3909][] @hamirmahal)

[#3912]: https://github.com/jsx-eslint/eslint-plugin-react/issues/3912
[#3910]: https://github.com/jsx-eslint/eslint-plugin-react/pull/3910
[#3909]: https://github.com/jsx-eslint/eslint-plugin-react/pull/3909
[#3651]: https://github.com/jsx-eslint/eslint-plugin-react/pull/3651

Expand Down
15 changes: 15 additions & 0 deletions docs/rules/jsx-no-constructed-context-values.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ return (
)
```

```jsx
import React from 'react';

const MyContext = React.createContext();
function Component() {
function foo() {}
return (<MyContext value={foo}></MyContext>);
}
```

Examples of **correct** code for this rule:

```jsx
Expand All @@ -33,6 +43,11 @@ return (
)
```

```jsx
const SomeContext = createContext();
const Component = () => <SomeContext value="Some string"><SomeContext>;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a slash missing in closing <SomeContext> -> </SomeContext>.

```

## Legitimate Uses

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.
Expand Down
59 changes: 52 additions & 7 deletions lib/rules/jsx-no-constructed-context-values.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,45 @@ function isConstruction(node, callScope) {
}
}

function isReactContext(context, node) {
let scope = getScope(context, node);
let variableScoping = null;
const contextName = node.name;

while (scope && !variableScoping) { // Walk up the scope chain to find the variable
variableScoping = scope.set.get(contextName);
scope = scope.upper;
}

if (!variableScoping) { // Context was not found in scope
return false;
}

// Get the variable's definition
const def = variableScoping.defs[0];

if (!def || def.node.type !== 'VariableDeclarator') {
return false;
}

const init = def.node.init; // Variable initializer

const isCreateContext = init
&& init.type === 'CallExpression'
&& (
(
init.callee.type === 'Identifier'
&& init.callee.name === 'createContext'
) || (
init.callee.type === 'MemberExpression'
&& init.callee.object.name === 'React'
&& init.callee.property.name === 'createContext'
)
);

return isCreateContext;
}

// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
Expand Down Expand Up @@ -148,14 +187,20 @@ module.exports = {
return {
JSXOpeningElement(node) {
const openingElementName = node.name;
if (openingElementName.type !== 'JSXMemberExpression') {
// Has no member
return;
}

const isJsxContext = openingElementName.property.name === 'Provider';
if (!isJsxContext) {
// Member is not Provider
if (openingElementName.type === 'JSXMemberExpression') {
const isJSXContext = openingElementName.property.name === 'Provider';
if (!isJSXContext) {
// Member is not Provider
return;
}
} else if (openingElementName.type === 'JSXIdentifier') {
const isJSXContext = isReactContext(context, openingElementName);
if (!isJSXContext) {
// Member is not context
return;
}
} else {
return;
}

Expand Down
96 changes: 96 additions & 0 deletions tests/lib/rules/jsx-no-constructed-context-values.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,44 @@ ruleTester.run('react-no-constructed-context-values', rule, {
);
`,
},
{
code: `
// Passes because the context is not a provider
function Component() {
return <MyContext.Consumer value={{ foo: 'bar' }} />;
}
`,
},
{
code: `
import React from 'react';

const MyContext = React.createContext();
const Component = () => <MyContext value={props}></MyContext>;
`,
},
{
code: `
import React from 'react';

const MyContext = React.createContext();
const Component = () => <MyContext value={100}></MyContext>;
`,
},
{
code: `
const SomeContext = createContext();
const Component = () => <SomeContext value="Some string"></SomeContext>;
`,
},
{
code: `
// Passes because MyContext is not a variable declarator
function Component({ MyContext }) {
return <MyContext value={{ foo: "bar" }} />;
}
`,
},
]),
invalid: parsers.all([
{
Expand Down Expand Up @@ -468,5 +506,63 @@ ruleTester.run('react-no-constructed-context-values', rule, {
},
],
},
{
// Invalid because function declaration creates a new identity
code: `
import React from 'react';

const Context = React.createContext();
function Component() {
function foo() {};
return (<Context value={foo}></Context>)
}
`,
errors: [
{
messageId: 'withIdentifierMsgFunc',
data: {
variableName: 'foo',
type: 'function declaration',
nodeLine: '6',
usageLine: '7',
},
},
],
},
{
// Invalid because the object value will create a new identity
code: `
const MyContext = createContext();
function Component() { const foo = {}; return (<MyContext value={foo}></MyContext>) }
`,
errors: [
{
messageId: 'withIdentifierMsg',
data: {
variableName: 'foo',
type: 'object',
nodeLine: '3',
usageLine: '3',
},
},
],
},
{
// Invalid because inline object construction will create a new identity
code: `
const MyContext = createContext();
function Component() { return (<MyContext value={{foo: "bar"}}></MyContext>); }
`,
errors: [
{
messageId: 'defaultMsg',
data: {
type: 'object',
nodeLine: '3',
usageLine: '3',
},
},
],
},
]),
});