Skip to content
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

[New] : Enforce no unused React elements #2903

Closed

Conversation

duncanbeevers
Copy link
Contributor

@duncanbeevers duncanbeevers commented Jan 14, 2021

React elements declared and then not used indicate a logic error.

eslint's built-in rule no-unused-expressions flags instances of side-effect-free, unused code.

The built-in rule does not flag unused React.createElement calls / JSX, recognizing them as possibly-side-effecting.

This PR adds a custom rule to flag unused React.createElement uses.

Even in a strongly-typed system, I managed to footgun myself with some early return clauses. This pseudo-code demonstrates the issue; The second guard clause does not return.

Code that would be flagged

function MyComponent(): ReactNode {
  const userStatus = useUserStatus();

  if (userStatus === UserStatus.Pending) {
    return <UserPending />;
  }

  if (userStatus === UserStatus.Error) {
    // Oops! I forgot to return
    <UserError />;
  }

  return <UserReady />;
}

@duncanbeevers duncanbeevers changed the title [New] : Enforce no unused React element expressions [New] : Enforce no unused React elements Jan 14, 2021
@ljharb
Copy link
Member

ljharb commented Jan 17, 2021

This is a bug in the built-in rule, then. A jsx element can’t be side-effecting, and an unused one should absolutely warn with no-unused-expressions.

Before adding a whole new rule here, can you file something on eslint itself?

@duncanbeevers
Copy link
Contributor Author

@ljharb

Before adding a whole new rule here, can you file something on eslint itself?

I confirmed that eslint proper doesn't flag these calls, and also that it does do a bit of JSX parsing.
Due to the overlap, I added this rule's functionality to the eslint's no-unused-expressions rule and opened this PR.

I've highlighted the differences between the PR opened on the core eslint rule and this one; they are summarized as:

  • It includes an escape hatch (allowJsx option) since some JSX pragmas may not be side-effect-free
  • It does not recognize literal React.createElement() calls; the original PR, focused on React, flagged these unused expressions

@duncanbeevers
Copy link
Contributor Author

Closing in favor of core rule no-unused-expressions; eslint/eslint#14012

@duncanbeevers duncanbeevers deleted the no-unused-expressions branch February 10, 2021 16:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

Successfully merging this pull request may close these issues.

None yet

2 participants