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

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

There is a newer version: 5.0.0.6962
Show newest version

Why is this an issue?

React components have built-in state data. This data is used to store component property values. When state changes, the component is re-rendered. React provides the useState hook to manage the state. useState returns a state variable retaining the data and a state setter function to update its value.

React will skip re-rendering the component and its children if the new value you provide is identical to the current state, as determined by an Object.is comparison. When the setter function is called with the state variable as a parameter, that comparison will always be true, and the component will never be re-rendered. This can happen by mistake when attempting to reset a default value or invert a boolean, among others.

This rule raises an issue when calling the setter function with the state variable provided by the same useState React hook.

import { useState } from "react";

function ShowLanguage() {
    const [language, setLanguage] = useState("fr-FR");
    return (
      <section>
        <h1>Your language is {language}!</h1>
        <button onClick={() => setLanguage(navigator.language)}>Detect language</button>
        <button onClick={() => setLanguage(language)}>Je préfère le français</button>{/* Non compliant: This button does nothing */}
      </section>
    );
};

Instead, you should call the setter with any parameter different from the state variable.

import { useState } from "react";

function ShowLanguage() {
    const [language, setLanguage] = useState("fr-FR");
    return (
      <section>
        <h1>Your language is {language}!</h1>
        <button onClick={() => setLanguage(navigator.language)}>Detect language</button>
        <button onClick={() => setLanguage("fr-FR")}>Je préfère le français</button>
      </section>
    );
};

Resources

Documentation





© 2015 - 2025 Weber Informatics LLC | Privacy Policy