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

Fix FP in S6442 improve corner case and fix rule title #3516

Closed
gabriel-vivas-sonarsource opened this issue Oct 28, 2022 · 0 comments · Fixed by #3622
Closed

Fix FP in S6442 improve corner case and fix rule title #3516

gabriel-vivas-sonarsource opened this issue Oct 28, 2022 · 0 comments · Fixed by #3622
Assignees
Labels
type: false positive Issue is reported when it should NOT be
Milestone

Comments

@gabriel-vivas-sonarsource
Label Description
Rule S6442 "React's useState used directly in render function"
Reproduce False positive on some edge cases where a derived state is intended.

Explanation

As pointed out by a user, there are some corner cases where you might legitimately want to call the state setter in the render, although inside a condition to avoid the infinite loop.

React discourages this pattern ("This pattern can be hard to understand and is usually best avoided"), but I guess it is a false positive nonetheless.

Suggestion

I suggest we ignore cases where the state setter is inside a conditional.
For example:

    const [language, setLanguage] = useState("fr-FR");

    if (enjoySharpKnives) {
        setLanguage(navigator.language);
    }

Perhaps we can go all the way and require an explicit return statement since this is what React is fundamentally doing internally.

    if (enjoySharpKnives) {
        setLanguage(navigator.language);
        return null;
    }

Corrections

The title of the rule says the opposite of what we want:

- React's useState hook should only be used in the render function or body of a component
+ React's useState hook should not be used directly in the render function or body of a component

While we are there, there are also extra semicolons in the code examples:

function ShowLanguage() {
    ...
-};
+}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: false positive Issue is reported when it should NOT be
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants