50 lines
2.2 KiB
Plaintext

== 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.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
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.
[source,javascript,diff-id=1,diff-type=compliant]
----
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
* React Documentation - https://react.dev/learn/state-a-components-memory[State: A Component's Memory]
* React Documentation - https://react.dev/reference/react/useState[useState]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is[Object.is()]