Skip to content

Commit e17848e

Browse files
committed
add new rule
1 parent 5f6350a commit e17848e

File tree

6 files changed

+463
-0
lines changed

6 files changed

+463
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ Enable the rules that you would like to use.
123123
* [react/no-find-dom-node](docs/rules/no-find-dom-node.md): Prevent usage of findDOMNode
124124
* [react/no-is-mounted](docs/rules/no-is-mounted.md): Prevent usage of isMounted
125125
* [react/no-multi-comp](docs/rules/no-multi-comp.md): Prevent multiple component definition per file
126+
* [react/no-object-type-as-default-prop](docs/rules/no-object-type-as-default-prop.md): Prevent usage of object types variables as default param in functional component
126127
* [react/no-redundant-should-component-update](docs/rules/no-redundant-should-component-update.md): Flag shouldComponentUpdate when extending PureComponent
127128
* [react/no-render-return-value](docs/rules/no-render-return-value.md): Prevent usage of the return value of React.render
128129
* [react/no-set-state](docs/rules/no-set-state.md): Prevent usage of setState
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# Prevent usage of referential-type variables as default param in functional component (react/no-object-type-as-default-prop)
2+
3+
Warns if in a functional component, an object type value (such as array/object literal) is used as default prop, to prevent potential un-necessary re-renders, and performance regressions.
4+
5+
## Rule Details
6+
7+
Certain values (like arrays, objects, functions, etc) are compared by indentity instead of by value. This means that, for example, whilst two empty arrays represent the same value - to the JS engine they are distinct and inequal as they represent two different identities in memory.
8+
9+
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 executed the JS engine will create a new, non-equal value in the destructured variable.
10+
11+
In the context of a React functional component's props argument this means that 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.
12+
13+
This obviously destroys any performance benefits you get from memoisation. Additionally in certain circumstances this can cause infinite rerender loops, which can often be hard to debug.
14+
15+
It's worth noting that primitive literal values (`string`, `number`, `boolean`, `null`, and `undefined`) are compared by value - meaning these are safe to use as inlined default destructured property values.
16+
17+
To fix the violations, the easiest way is to use a referencing variable instead of using the literal values, e.g:
18+
19+
```
20+
const emptyArray = [];
21+
22+
function Component({
23+
items = emptyArray,
24+
}) {}
25+
```
26+
27+
Examples of ***invalid*** code for this rule:
28+
29+
```jsx
30+
function Component({
31+
items = [],
32+
}) {}
33+
34+
const Component = ({
35+
items = {},
36+
}) => {}
37+
38+
const Component = ({
39+
items = () => {},
40+
}) => {}
41+
```
42+
43+
Examples of ***valid*** code for this rule:
44+
45+
```jsx
46+
const emptyArray = [];
47+
48+
function Component({
49+
items = emptyArray,
50+
}) {}
51+
52+
const emptyObject = {};
53+
const Component = ({
54+
items = emptyObject,
55+
}) => {}
56+
57+
const noopFunc = () => {};
58+
const Component = ({
59+
items = noopFunc,
60+
}) => {}
61+
62+
// primitive literals are all compared by value, so are safe to be inlined
63+
function Component({
64+
num = 3,
65+
str = 'foo',
66+
bool = true,
67+
}) {}
68+
```

index.js

+1
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ const allRules = {
6767
'no-find-dom-node': require('./lib/rules/no-find-dom-node'),
6868
'no-is-mounted': require('./lib/rules/no-is-mounted'),
6969
'no-multi-comp': require('./lib/rules/no-multi-comp'),
70+
'no-object-type-as-default-prop': require('./lib/rules/no-object-type-as-default-prop'),
7071
'no-set-state': require('./lib/rules/no-set-state'),
7172
'no-string-refs': require('./lib/rules/no-string-refs'),
7273
'no-redundant-should-component-update': require('./lib/rules/no-redundant-should-component-update'),
+152
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
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 docsUrl = require('../util/docsUrl');
9+
10+
const FORBIDDEN_TYPES_MAP = {
11+
ArrowFunctionExpression: 'arrow function',
12+
FunctionExpression: 'function expression',
13+
ObjectExpression: 'object literal',
14+
ArrayExpression: 'array literal',
15+
ClassExpression: 'class expression',
16+
NewExpression: 'construction expression',
17+
JSXElement: 'JSX element'
18+
};
19+
20+
const FORBIDDEN_TYPES = new Set(Object.keys(FORBIDDEN_TYPES_MAP));
21+
const MESSAGE_ID = 'forbiddenTypeDefaultParam';
22+
23+
function isReactComponentName(node) {
24+
if (node.id && node.id.type === 'Identifier' && node.id.name) {
25+
const firstLetter = node.id.name[0];
26+
if (firstLetter.toUpperCase() === firstLetter) {
27+
return true;
28+
}
29+
}
30+
31+
return false;
32+
}
33+
34+
function isReactComponentVariableDeclarator(variableDeclarator) {
35+
if (!isReactComponentName(variableDeclarator)) {
36+
return false;
37+
}
38+
return (
39+
variableDeclarator.init != null
40+
&& variableDeclarator.init.type === 'ArrowFunctionExpression'
41+
);
42+
}
43+
44+
function hasUsedObjectDestructuringSyntax(params) {
45+
if (
46+
params == null
47+
|| params.length !== 1
48+
|| params[0].type !== 'ObjectPattern'
49+
) {
50+
return false;
51+
}
52+
return true;
53+
}
54+
55+
function verifyDefaultPropsDestructuring(context, properties) {
56+
// Loop through each of the default params
57+
properties.forEach((prop) => {
58+
if (prop.type !== 'Property') {
59+
return;
60+
}
61+
62+
const propName = prop.key.name;
63+
const propDefaultValue = prop.value;
64+
65+
if (propDefaultValue.type !== 'AssignmentPattern') {
66+
return;
67+
}
68+
69+
const propDefaultValueType = propDefaultValue.right.type;
70+
71+
if (
72+
propDefaultValueType === 'Literal'
73+
&& propDefaultValue.right.regex != null
74+
) {
75+
context.report({
76+
node: propDefaultValue,
77+
messageId: MESSAGE_ID,
78+
data: {
79+
propName,
80+
forbiddenType: 'regex literal'
81+
}
82+
});
83+
} else if (propDefaultValueType === 'CallExpression'
84+
&& propDefaultValue.right.callee.type === 'MemberExpression'
85+
&& propDefaultValue.right.callee.object.type === 'Identifier'
86+
&& propDefaultValue.right.callee.object.name === 'Symbol'
87+
&& propDefaultValue.right.callee.property.name === 'for'
88+
) {
89+
context.report({
90+
node: propDefaultValue,
91+
messageId: MESSAGE_ID,
92+
data: {
93+
propName,
94+
forbiddenType: 'Symbol.for literal'
95+
}
96+
});
97+
} else if (FORBIDDEN_TYPES.has(propDefaultValueType)) {
98+
context.report({
99+
node: propDefaultValue,
100+
messageId: MESSAGE_ID,
101+
data: {
102+
propName,
103+
forbiddenType: FORBIDDEN_TYPES_MAP[propDefaultValueType]
104+
}
105+
});
106+
}
107+
});
108+
}
109+
110+
module.exports = {
111+
meta: {
112+
docs: {
113+
description: 'Prevent usage of referential-type variables as default param in functional component',
114+
category: 'Best Practices',
115+
recommended: false,
116+
url: docsUrl('no-object-type-as-default-prop')
117+
},
118+
messages: {
119+
[MESSAGE_ID]:
120+
'{{propName}} has a/an {{forbiddenType}} as default prop.\n'
121+
+ 'This could lead to potential infinite render loop in React. \n'
122+
+ 'Use a variable reference instead of {{forbiddenType}}.'
123+
}
124+
},
125+
create(context) {
126+
return {
127+
FunctionDeclaration(node) {
128+
if (
129+
!isReactComponentName(node)
130+
|| !hasUsedObjectDestructuringSyntax(node.params)
131+
) {
132+
return;
133+
}
134+
135+
const properties = node.params[0].properties;
136+
verifyDefaultPropsDestructuring(context, properties);
137+
},
138+
'VariableDeclarator > :matches(ArrowFunctionExpression, FunctionExpression).init'(
139+
node
140+
) {
141+
if (
142+
!isReactComponentVariableDeclarator(node.parent)
143+
|| !hasUsedObjectDestructuringSyntax(node.params)
144+
) {
145+
return;
146+
}
147+
const properties = node.params[0].properties;
148+
verifyDefaultPropsDestructuring(context, properties);
149+
}
150+
};
151+
}
152+
};

tests/lib/.DS_Store

6 KB
Binary file not shown.

0 commit comments

Comments
 (0)