All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.javascript.rules.javascript.S6754.html Maven / Gradle / Ivy

There is a newer version: 10.17.0.28100
Show newest version

Why is this an issue?

In React, useState is a hook that allows functional components to manage and update state in a manner similar to class components. When you use the useState hook, it returns an array with two values: the current state value and a function to update that state value.

Destructuring these values and naming them symmetrically (i.e., using consistent variable names for both the current state and the update function) is a recommended best practice:

  • When you destructure and name the values symmetrically, it makes your code more readable and self-explanatory. Other developers can quickly understand the purpose of each variable without needing to refer back to the useState function call.
  • Following a naming convention where the state variable and its corresponding update function have similar names is a common practice in the React community. It helps maintain consistency and makes it easier for others to understand your code.
  • If you don’t name the variables symmetrically, it can lead to confusion, especially in larger components or when multiple state variables are involved. You might accidentally use the wrong variable when updating the state, which can result in bugs that are hard to track down.
import { useState } from 'react';
function MyComponent() {
  const [count, update] = useState(0); // Noncompliant
  return <div onClick={() => update(count + 1)}>{count}</div>
}

You should destructure the return value of useState calls in terms of the current state and a function to update that state and name them symmetrically.

import { useState } from 'react';
function MyComponent() {
  const [count, setCount] = useState(0);
  return <div onClick={() => setCount(count + 1)}>{count}</div>
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy