React Hooks Warnings (unused variables)

  • ALM used (GitHub, Bitbucket Cloud, Azure DevOps)
    GitHub
  • Languages of the repository
    React

I’m getting many warnings related to variables not being used. These are hooks setters and getters. For example:
const [state, setState] = useState();
Sometimes “state” is not used, so my question is, if I write this:
const [,setState] = useState()
to accomodate for the warning, it just looks wrong, and pontentially buggy code, it does not look like React code, readability is compromised, and there’s a potential bug if that comma is omitted.

Then it also happens that the setter is not used, and I could just leave it out, and even though I don’t see potential problems with that, it still does not look like react code.

What should I do? Or is there a setting to adjust to tell sonarcloud that is is JSX / react code and not plain JS?
Thanks.

Hello Daniel,

Welcome to SonarSource community, and thank you for your message!

I understand your argument, but I am afraid I don’t share it. Declaring a variable that is not going to be used makes the code more suspicious than anything else. While reading your code, somebody would wonder whether that variable was unused on purpose or the author of the code just forgot to use it at some point, thus questioning whether the code is correct.

With regard to your comment about the code not looking as React code or looking buggy, I don’t agree either. Using array destructuring and ignoring an item is neither wrong nor weird, it’s JavaScript programming. Also, what React code should look like is a bit subjective in my opinion. Just saying, Facebook (the author of React incidentally) actually does use this very same pattern in React’s code base itself here.

Long story short, YAGNI :slight_smile:

Hope this helps,
Yassin

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.