Skip to content

Add React Performance checks for array-literal and object-literal props. #159

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

Closed
Closed
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
83 changes: 83 additions & 0 deletions src/rules/jsxNoArrayLiteralPropsRule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* @license
* Copyright 2016 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as Lint from "tslint";
import { isJsxAttribute, isJsxExpression } from "tsutils";
import * as ts from "typescript";

export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "jsx-no-array-literal-props",
description: "Checks for array literals used in JSX attributes",
descriptionDetails: Lint.Utils.dedent
`Creating new arrays inside the render call stack works against pure component \
rendering. When doing an equality check between two arrays, React will always \
consider them unequal values and force the component to re-render more often than necessary.`,
options: null,
optionsDescription: "",
optionExamples: ["true"],
type: "functionality",
typescriptOnly: false,
};
/* tslint:enable:object-literal-sort-keys */

/* tslint:disable-next-line max-line-length */
public static FAILURE_STRING = "Array literal properties are forbidden in JSX attributes due to their rendering performance impact";

public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk);
}
}

function walk(ctx: Lint.WalkContext<void>) {
return ts.forEachChild(ctx.sourceFile, function cb(node: ts.Node): void {
// continue iterations until JsxAttribute will be found
if (isJsxAttribute(node)) {
const { initializer } = node;
// early exit in case when initializer is string literal or not provided (e.d. `disabled`)
if (initializer === undefined || !isJsxExpression(initializer)) {
return;
}

// Ignore "ref" attribute.
// ref is not part of the props so using lambdas here will not trigger useless re-renders
if (node.name.text === "ref") {
return;
}

const { expression } = initializer;
if (expression !== undefined && isArrayLiteral(expression)) {
return ctx.addFailureAtNode(expression, Rule.FAILURE_STRING);
}
}
return ts.forEachChild(node, cb);
});
}

function isArrayLiteral(node: ts.Node): boolean {
switch (node.kind) {
case ts.SyntaxKind.ArrayLiteralExpression:
return true;

case ts.SyntaxKind.ParenthesizedExpression:
return isArrayLiteral((node as ts.ParenthesizedExpression).expression);

default:
return false;
}
}
84 changes: 84 additions & 0 deletions src/rules/jsxNoObjectLiteralPropsRule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* @license
* Copyright 2016 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as Lint from "tslint";
import { isJsxAttribute, isJsxExpression } from "tsutils";
import * as ts from "typescript";

export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "jsx-no-object-literal-props",
description: "Checks for object literals used in JSX attributes",
descriptionDetails: Lint.Utils.dedent
`Creating new objects inside the render call stack works against pure component \
rendering. When doing an equality check between two objects, React will always \
consider them unequal values and force the component to re-render more often than necessary.`,
options: null,
optionsDescription: "",
optionExamples: ["true"],
type: "functionality",
typescriptOnly: false,
};
/* tslint:enable:object-literal-sort-keys */

/* tslint:disable-next-line max-line-length */
public static FAILURE_STRING = "Object literal properties are forbidden in JSX attributes due to their rendering performance impact";

public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk);
}
}

function walk(ctx: Lint.WalkContext<void>) {
return ts.forEachChild(ctx.sourceFile, function cb(node: ts.Node): void {
// continue iterations until JsxAttribute will be found
if (isJsxAttribute(node)) {
const { initializer } = node;
// early exit in case when initializer is string literal or not provided (e.d. `disabled`)
if (initializer === undefined || !isJsxExpression(initializer)) {
return;
}

// Ignore "ref" attribute.
// ref is not part of the props so using lambdas here will not trigger useless re-renders
if (node.name.text === "ref") {
return;
}

const { expression } = initializer;
if (expression !== undefined && isObjectLiteral(expression)) {
return ctx.addFailureAtNode(expression, Rule.FAILURE_STRING);
}
}

return ts.forEachChild(node, cb);
});
}

function isObjectLiteral(node: ts.Node): boolean {
switch (node.kind) {
case ts.SyntaxKind.ObjectLiteralExpression:
return true;

case ts.SyntaxKind.ParenthesizedExpression:
return ts.isObjectLiteralExpression((node as ts.ParenthesizedExpression).expression);

default:
return false;
}
}
22 changes: 22 additions & 0 deletions test/rules/jsx-no-array-literal-props/test.tsx.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const ary = []
const good = <Foo bar="car" car dar={ary} />;

const bad = <Foo bar={[]} />
~~ [Array literal properties are forbidden in JSX attributes due to their rendering performance impact]

function goodRender() {
const ary = this.props.ary
return (
<div className="red" ary={ary} />
);
}


function badRender_DynamicExpression() {
return (
<div bar={[]}
~~ [Array literal properties are forbidden in JSX attributes due to their rendering performance impact]
);
}

// TODO: Check splat properties, render local variables
5 changes: 5 additions & 0 deletions test/rules/jsx-no-array-literal-props/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"jsx-no-array-literal-props": true
}
}
21 changes: 21 additions & 0 deletions test/rules/jsx-no-object-literal-props/test.tsx.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const jsx = <div />
const good = <Foo bar="car" car dar={() => {a: true}} />;

const bad = <Foo bar={{a: true}} />
~~~~~~~~~ [Object literal properties are forbidden in JSX attributes due to their rendering performance impact]

function goodRender() {
const v = this.props.v
return (
<div className="red" v={v} />
);
}

function badRender_DynamicExpression() {
return (
<div bar={{a: true}}
~~~~~~~~~ [Object literal properties are forbidden in JSX attributes due to their rendering performance impact]
);
}

// TODO: Check splat properties, render local variables
5 changes: 5 additions & 0 deletions test/rules/jsx-no-object-literal-props/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"jsx-no-object-literal-props": true
}
}
2 changes: 2 additions & 0 deletions tslint-react.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
"jsx-key": true,
"jsx-no-bind": true,
"jsx-no-lambda": true,
"jsx-no-array-literal-props": true,
"jsx-no-object-literal-props": true,
"jsx-no-multiline-js": true,
"jsx-no-string-ref": true,
"jsx-self-close": true,
Expand Down