Introducing 7 new rules for React which detect bugs in JS/TS code

Hi everyone,

This is a big release where we focused on catching React-specific bugs and code smells.

We have 7 new rules for React:

  • S6440: Ensure Hooks are always called from the top of React function Components. This helps when first starting with hooks, while also catching some mistakes that might be hard to see otherwise. See React’s own Rules of Hooks.
  • S6441: Detect methods of React component classes that are not used inside the Component. Lifecycle methods are excluded. Overall, this helps detect dead code but importantly it also catches uses of methods outside the components. This goes against React’s data model and can break many assumptions. See the details for ways to solve it.
  • S6442: Prevent hooks from being called directly in the body of components, which causes an infinite render loop. This can happen by accident or when you’re starting to learn hooks. See the relevant meme on Twitter.
  • S6443: Ensure a Hook’ setter is not called with the current state. This does nothing, so it is very likely a mistake, like a forgotten Boolean inversion or something else.
  • S6438: When starting with JSX you might not know that regular comments produce an unexpected DOM node. That can be quite surprising, but now you’re safe with this rule.
  • S6435: Detect when you forget to return from a React class component. This can happen by mistake and React won’t complain so it can be hard to find!
  • S6439: Prevents accidentally rendering unexpected characters that come from conditionals in JSX. See the rule details for some examples. Did you know about this?

Some improvements:

  • S1534: Now detects duplicated attributes in JSX literals. This helps with typos and duplicates quite a lot!
  • S2589: No longer raises an issue for expressions passed as children for JSX literals. That means fewer false positives.
  • S905: Now helps detect missing return statements in React function components. Similar to what S6435 does in class components.
  • S5148: Now handles an additional edge case to help secure your code when opening Browser windows programmatically.
  • S1135: Now covers an edge case where TODOs were not being seen. It’s all in the details.

All of this is available now in SonarCloud and will be on SonarQube 9.6 and in SonarLint when released.

Stay tuned for more things to come for React :wink:
Please share any feedback. Enjoy!