Skip to content

Commit 4cfe5d2

Browse files
cyan33fengkxljharb
committed
[New] add no-object-type-as-default-prop rule
Co-authored-by: cyan33 <[email protected]> Co-authored-by: fengkx <[email protected]> Co-authored-by: Jordan Harband <[email protected]>
1 parent bf59919 commit 4cfe5d2

File tree

6 files changed

+371
-0
lines changed

6 files changed

+371
-0
lines changed

CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,15 @@ This change log adheres to standards from [Keep a CHANGELOG](https://keepachange
99
* support new config system ([#3429][] @jjangga0214)
1010
* [`hook-use-state`]: add `allowDestructuredState` option ([#3449][] @ljharb)
1111
* add [`sort-default-props`] and deprecate [`jsx-sort-default-props`] ([#1861][] @alexzherdev)
12+
* add [`no-object-type-as-default-prop`] rule ([#2848][] @cyan33 @fengkx)
1213

1314
### Changed
1415
* [Perf] component detection: improve performance by avoiding traversing parents unnecessarily ([#3459][] @golopot)
1516

1617
[#3459]: https://github.com/jsx-eslint/eslint-plugin-react/pull/3459
1718
[#3449]: https://github.com/jsx-eslint/eslint-plugin-react/pull/3449
1819
[#3424]: https://github.com/jsx-eslint/eslint-plugin-react/pull/3429
20+
[#2848]: https://github.com/jsx-eslint/eslint-plugin-react/pull/2848
1921
[#1861]: https://github.com/jsx-eslint/eslint-plugin-react/pull/1861
2022

2123
### Fixed
@@ -4011,6 +4013,7 @@ If you're still not using React 15 you can keep the old behavior by setting the
40114013
[`no-is-mounted`]: docs/rules/no-is-mounted.md
40124014
[`no-multi-comp`]: docs/rules/no-multi-comp.md
40134015
[`no-namespace`]: docs/rules/no-namespace.md
4016+
[`no-object-type-as-default-prop`]: docs/rules/no-object-type-as-default-prop.md
40144017
[`no-redundant-should-component-update`]: docs/rules/no-redundant-should-component-update.md
40154018
[`no-render-return-value`]: docs/rules/no-render-return-value.md
40164019
[`no-set-state`]: docs/rules/no-set-state.md

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,7 @@ module.exports = [
315315
|| | | [react/no-is-mounted](docs/rules/no-is-mounted.md) | Disallow usage of isMounted |
316316
| | | | [react/no-multi-comp](docs/rules/no-multi-comp.md) | Disallow multiple component definition per file |
317317
| | | | [react/no-namespace](docs/rules/no-namespace.md) | Enforce that namespaces are not used in React elements |
318+
| | | | [react/no-object-type-as-default-prop](docs/rules/no-object-type-as-default-prop.md) | Disallow usage of referential-type variables as default param in functional component |
318319
| | | | [react/no-redundant-should-component-update](docs/rules/no-redundant-should-component-update.md) | Disallow usage of shouldComponentUpdate when extending React.PureComponent |
319320
|| | | [react/no-render-return-value](docs/rules/no-render-return-value.md) | Disallow usage of the return value of ReactDOM.render |
320321
| | | | [react/no-set-state](docs/rules/no-set-state.md) | Disallow usage of setState |

configs/all.js

+1
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ const allRules = {
8888
'no-unused-class-component-methods': require('../lib/rules/no-unused-class-component-methods'),
8989
'no-unused-prop-types': require('../lib/rules/no-unused-prop-types'),
9090
'no-unused-state': require('../lib/rules/no-unused-state'),
91+
'no-object-type-as-default-prop': require('../lib/rules/no-object-type-as-default-prop'),
9192
'no-will-update-set-state': require('../lib/rules/no-will-update-set-state'),
9293
'prefer-es6-class': require('../lib/rules/prefer-es6-class'),
9394
'prefer-exact-props': require('../lib/rules/prefer-exact-props'),
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Disallow usage of referential-type variables as default param in functional component (react/no-object-type-as-default-prop)
2+
3+
💼 This rule is enabled in the following [configs](https://github.com/jsx-eslint/eslint-plugin-react#shareable-configurations): `all`.
4+
5+
Warns if in a functional component, an object type value (such as array/object literal/function/etc) is used as default prop, to prevent potential unnecessary rerenders, and performance regressions.
6+
7+
## Rule Details
8+
9+
Certain values (like arrays, objects, functions, etc) are compared by identity instead of by value. This means that, for example, whilst two empty arrays conceptually represent the same value - JavaScript semantics dictate that they are distinct and unequal as they represent two distinct values.
10+
11+
When using object destructuring syntax you can set the default value for a given property if it does not exist. If you set the default value to one of the values that is compared by identity, it will mean that each time the destructure is evaluated the JS engine will create a new, distinct value in the destructured variable.
12+
13+
In the context of a React functional component's props argument this means for each render, the property has a new, distinct value. When this value is passed to a hook as a dependency or passed into a child component as a property React will see this as a new value - meaning that a hook will be re-evaluated, or a memoized component will rerender.
14+
15+
This obviously destroys any performance benefits you get from memoization. Additionally, in certain circumstances this can cause infinite rerender loops, which can often be hard to debug.
16+
17+
It's worth noting that primitive literal values (`string`, `number`, `boolean`, `null`, and `undefined`) can be considered to be compared "by value", or alternatively, as always having the same identity (every `3` is the same exact `3`). Thus, it's safe for those to be inlined as a default value.
18+
19+
To fix the violations, the easiest way is to use a referencing variable in module scope instead of using the literal values, e.g:
20+
21+
```jsx
22+
const emptyArray = [];
23+
24+
function Component({
25+
items = emptyArray,
26+
}) {}
27+
```
28+
29+
Examples of ***invalid*** code for this rule:
30+
31+
```jsx
32+
function Component({
33+
items = [],
34+
}) {}
35+
36+
const Component = ({
37+
items = {},
38+
}) => {}
39+
40+
const Component = ({
41+
items = () => {},
42+
}) => {}
43+
```
44+
45+
Examples of ***valid*** code for this rule:
46+
47+
```jsx
48+
const emptyArray = [];
49+
50+
function Component({
51+
items = emptyArray,
52+
}) {}
53+
54+
const emptyObject = {};
55+
const Component = ({
56+
items = emptyObject,
57+
}) => {}
58+
59+
const noopFunc = () => {};
60+
const Component = ({
61+
items = noopFunc,
62+
}) => {}
63+
64+
// primitives are all compared by value, so are safe to be inlined
65+
function Component({
66+
num = 3,
67+
str = 'foo',
68+
bool = true,
69+
}) {}
70+
```
+108
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/**
2+
* @fileoverview Prevent usage of referential-type variables as default param in functional component
3+
* @author Chang Yan
4+
*/
5+
6+
'use strict';
7+
8+
const values = require('object.values');
9+
10+
const Components = require('../util/Components');
11+
const docsUrl = require('../util/docsUrl');
12+
const report = require('../util/report');
13+
14+
const FORBIDDEN_TYPES_MAP = {
15+
ArrowFunctionExpression: 'arrow function',
16+
FunctionExpression: 'function expression',
17+
ObjectExpression: 'object literal',
18+
ArrayExpression: 'array literal',
19+
ClassExpression: 'class expression',
20+
NewExpression: 'construction expression',
21+
JSXElement: 'JSX element',
22+
};
23+
24+
const FORBIDDEN_TYPES = new Set(Object.keys(FORBIDDEN_TYPES_MAP));
25+
const MESSAGE_ID = 'forbiddenTypeDefaultParam';
26+
27+
const messages = {
28+
[MESSAGE_ID]: '{{propName}} has a/an {{forbiddenType}} as default prop. This could lead to potential infinite render loop in React. Use a variable reference instead of {{forbiddenType}}.',
29+
};
30+
function hasUsedObjectDestructuringSyntax(params) {
31+
return (
32+
params != null
33+
&& params.length === 1
34+
&& params[0].type === 'ObjectPattern'
35+
);
36+
}
37+
38+
function verifyDefaultPropsDestructuring(context, properties) {
39+
// Loop through each of the default params
40+
properties.filter((prop) => prop.type === 'Property').forEach((prop) => {
41+
const propName = prop.key.name;
42+
const propDefaultValue = prop.value;
43+
44+
if (propDefaultValue.type !== 'AssignmentPattern') {
45+
return;
46+
}
47+
48+
const propDefaultValueType = propDefaultValue.right.type;
49+
50+
if (
51+
propDefaultValueType === 'Literal'
52+
&& propDefaultValue.right.regex != null
53+
) {
54+
report(context, messages[MESSAGE_ID], MESSAGE_ID, {
55+
node: propDefaultValue,
56+
data: {
57+
propName,
58+
forbiddenType: 'regex literal',
59+
},
60+
});
61+
} else if (
62+
propDefaultValueType === 'CallExpression'
63+
&& propDefaultValue.right.callee.type === 'Identifier'
64+
&& propDefaultValue.right.callee.name === 'Symbol'
65+
) {
66+
report(context, messages[MESSAGE_ID], MESSAGE_ID, {
67+
node: propDefaultValue,
68+
data: {
69+
propName,
70+
forbiddenType: 'Symbol literal',
71+
},
72+
});
73+
} else if (FORBIDDEN_TYPES.has(propDefaultValueType)) {
74+
report(context, messages[MESSAGE_ID], MESSAGE_ID, {
75+
node: propDefaultValue,
76+
data: {
77+
propName,
78+
forbiddenType: FORBIDDEN_TYPES_MAP[propDefaultValueType],
79+
},
80+
});
81+
}
82+
});
83+
}
84+
85+
module.exports = {
86+
meta: {
87+
docs: {
88+
description: 'Disallow usage of referential-type variables as default param in functional component',
89+
category: 'Best Practices',
90+
recommended: false,
91+
url: docsUrl('no-object-type-as-default-prop'),
92+
},
93+
messages,
94+
},
95+
create: Components.detect((context, components) => ({
96+
'Program:exit'() {
97+
const list = components.list();
98+
values(list).forEach((component) => {
99+
const node = component.node;
100+
if (!hasUsedObjectDestructuringSyntax(node.params)) {
101+
return;
102+
}
103+
const properties = node.params[0].properties;
104+
verifyDefaultPropsDestructuring(context, properties);
105+
});
106+
},
107+
})),
108+
};

0 commit comments

Comments
 (0)