Skip to content

Commit

Permalink
Add rule S6754 (hook-use-state): The return value of "useState" sho…
Browse files Browse the repository at this point in the history
…uld be destructured and named symmetrically (#4152)
  • Loading branch information
yassin-kammoun-sonarsource authored Sep 12, 2023
1 parent 8644f60 commit 746e232
Show file tree
Hide file tree
Showing 13 changed files with 291 additions and 0 deletions.
31 changes: 31 additions & 0 deletions its/ruling/src/test/expected/js/jira-clone/javascript-S6754.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"jira-clone:client/src/Project/Board/IssueDetails/Comments/Comment/index.jsx": [
27,
28
],
"jira-clone:client/src/Project/Board/IssueDetails/Comments/Create/index.jsx": [
18,
19
],
"jira-clone:client/src/Project/Board/IssueDetails/Description/index.jsx": [
16
],
"jira-clone:client/src/shared/components/ConfirmModal/index.jsx": [
36
],
"jira-clone:client/src/shared/components/CopyLinkButton.jsx": [
7
],
"jira-clone:client/src/shared/components/DatePicker/index.jsx": [
26
],
"jira-clone:client/src/shared/components/Modal/index.jsx": [
44
],
"jira-clone:client/src/shared/components/Select/Dropdown.jsx": [
47
],
"jira-clone:client/src/shared/components/Select/index.jsx": [
71
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"react-cloud-music:src/application/Player/index.jsx": [
25
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"courselit:apps/web/components/admin/media/index.tsx": [
59
],
"courselit:apps/web/components/public/lesson-viewer.tsx": [
80
]
}
86 changes: 86 additions & 0 deletions its/ruling/src/test/expected/ts/eigen/typescript-S6754.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
{
"eigen:src/app/Components/Artist/ArtistArtworks/ArtistArtworks.tsx": [
41
],
"eigen:src/app/Components/Gene/GeneArtworks.tsx": [
89
],
"eigen:src/app/Components/HeaderArtworksFilter/HeaderArtworksFilter.tsx": [
59
],
"eigen:src/app/Components/PopoverMessage/PopoverMessageProvider.tsx": [
29,
30
],
"eigen:src/app/Components/StickyTabPage/StickyTabPageTabBar.tsx": [
24
],
"eigen:src/app/Components/Tag/TagArtworks.tsx": [
91
],
"eigen:src/app/Components/Toast/ToastComponent.tsx": [
38
],
"eigen:src/app/Scenes/About/About.tsx": [
16
],
"eigen:src/app/Scenes/ArtistSeries/ArtistSeries.tsx": [
33
],
"eigen:src/app/Scenes/Artwork/Components/CommercialButtons/CollapsibleArtworkDetails.tsx": [
41
],
"eigen:src/app/Scenes/Collection/Components/CollectionArtworksFilter.tsx": [
18
],
"eigen:src/app/Scenes/Fair/Fair.tsx": [
59
],
"eigen:src/app/Scenes/Fair/FairAllFollowedArtists.tsx": [
33
],
"eigen:src/app/Scenes/Home/Components/EmailConfirmationBanner.tsx": [
17,
18
],
"eigen:src/app/Scenes/Inbox/Components/Conversations/CTAPopUp.tsx": [
5
],
"eigen:src/app/Scenes/MyCollection/Screens/ArtworkForm/Components/Rarity.tsx": [
13
],
"eigen:src/app/Scenes/MyCollection/Screens/Insights/AverageSalePriceAtAuction.tsx": [
18
],
"eigen:src/app/Scenes/Sale/Sale.tsx": [
83,
84
],
"eigen:src/app/Scenes/Search/SearchArtworksGrid.tsx": [
34
],
"eigen:src/app/navigation/NavStack.tsx": [
27
],
"eigen:src/app/utils/LinkedAccounts/apple.ts": [
15
],
"eigen:src/app/utils/LinkedAccounts/facebook.ts": [
11
],
"eigen:src/app/utils/LinkedAccounts/google.ts": [
16
],
"eigen:src/app/utils/useGlobalState.ts": [
4
],
"eigen:src/palette/elements/Select/Select.tsx": [
228
],
"eigen:src/palette/elements/Select/SelectV2.tsx": [
186
],
"eigen:src/palette/organisms/screenStructure/Screen.tsx": [
36
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"searchkit:packages/searchkit-client/src/searchkit.tsx": [
243
],
"searchkit:packages/searchkit-sdk/src/react-hooks/index.ts": [
9
]
}
1 change: 1 addition & 0 deletions packages/jsts/src/linter/quickfixes/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ export const quickFixRules = new Set([
'prefer-while',

// eslint-plugin-react
'hook-use-state',
'jsx-no-useless-fragment',
'no-unknown-property',

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { useState } from 'react';
function useSomething() {
const [state, , setState] = useState();
return [state, setState];
}
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ public static List<Class<? extends JavaScriptCheck>> getAllChecks() {
HardcodedCredentialsCheck.class,
HashingCheck.class,
HiddenFilesCheck.class,
HookUseStateCheck.class,
IdenticalExpressionOnBinaryOperatorCheck.class,
IdenticalFunctionsCheck.class,
IgnoredReturnCheck.class,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.javascript.checks;

import java.util.Collections;
import java.util.List;
import org.sonar.check.Rule;
import org.sonar.plugins.javascript.api.EslintBasedCheck;
import org.sonar.plugins.javascript.api.JavaScriptRule;
import org.sonar.plugins.javascript.api.TypeScriptRule;

@JavaScriptRule
@TypeScriptRule
@Rule(key = "S6754")
public class HookUseStateCheck implements EslintBasedCheck {

@Override
public String eslintKey() {
return "hook-use-state";
}

@Override
public List<Object> configurations() {
return Collections.singletonList(new Config());
}

static class Config {

boolean allowDestructuredState = true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<h2>Why is this an issue?</h2>
<p>In React, <code>useState</code> is a hook that allows functional components to manage and update state in a manner similar to class components.
When you use the <code>useState</code> hook, it returns an array with two values: the current state value and a function to update that state
value.</p>
<p>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:</p>
<ul>
<li> 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 <code>useState</code> function call. </li>
<li> 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. </li>
<li> 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. </li>
</ul>
<pre data-diff-id="1" data-diff-type="noncompliant">
import { useState } from 'react';
function MyComponent() {
const [count, update] = useState(0); // Noncompliant
return &lt;div onClick={() =&gt; update(count + 1)}&gt;{count}&lt;/div&gt;
}
</pre>
<p>You should destructure the return value of <code>useState</code> calls in terms of the current state and a function to update that state and name
them symmetrically.</p>
<pre data-diff-id="1" data-diff-type="compliant">
import { useState } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
return &lt;div onClick={() =&gt; setCount(count + 1)}&gt;{count}&lt;/div&gt;
}
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
<li> <a href="https://react.dev/reference/react/useState">React - useState</a> </li>
</ul>

Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"title": "The return value of \"useState\" should be destructured and named symmetrically",
"type": "CODE_SMELL",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-6754",
"sqKey": "S6754",
"scope": "All",
"quickfix": "covered",
"code": {
"impacts": {
"MAINTAINABILITY": "HIGH",
"RELIABILITY": "MEDIUM",
"SECURITY": "LOW"
},
"attribute": "CONVENTIONAL"
},
"compatibleLanguages": [
"JAVASCRIPT",
"TYPESCRIPT"
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@
"S6748",
"S6749",
"S6750",
"S6754",
"S6756"
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.javascript.checks;

import static org.assertj.core.api.Assertions.assertThat;

import com.google.gson.Gson;
import org.junit.jupiter.api.Test;

class HookUseStateCheckTest {

@Test
void configurations() {
String configAsString = new Gson().toJson(new HookUseStateCheck().configurations());
assertThat(configAsString).isEqualTo("[{\"allowDestructuredState\":true}]");
}
}

0 comments on commit 746e232

Please sign in to comment.