42 lines
1.6 KiB
Plaintext
42 lines
1.6 KiB
Plaintext
![]() |
React components have a built-in `state` data. This data is used to store component property values. When `state` changes, the component is re-rendered. For functional components to manage `state`, React provides the `useState` hook, which returns the state value and a setter function to update its value.
|
||
|
|
||
|
When the setter function is called with the state variable as a parameter, nothing will happen. 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.
|
||
|
|
||
|
== Noncompliant Code Example
|
||
|
|
||
|
[source,javascript]
|
||
|
----
|
||
|
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>
|
||
|
);
|
||
|
};
|
||
|
----
|
||
|
|
||
|
== Compliant Solution
|
||
|
|
||
|
[source,javascript]
|
||
|
----
|
||
|
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>
|
||
|
);
|
||
|
};
|
||
|
----
|