React’s useState
hook setter function should not be called directly in the body of a component, as it would produce an infinite render
loop. A re-rendering occurs whenever the state of a component changes. Since a hook setter function changes the component’s state, it also triggers
re-rendering.
The loop "state updates → triggers re-render → state updates → triggers re-render → …" will continue indefinitely.
import { useState } from "react";
function ShowLanguage() {
const [language, setLanguage] = useState("fr-FR");
setLanguage(navigator.language); // Noncompliant: causes an infinite loop
return (
<section>
<h1>Your language is {language}!</h1>
<button onClick={() => setLanguage("fr-FR")}>Je préfère le français</button>
</section>
);
}
Instead, the setter function should be called from an event handler.
import { useState } from "react";
function ShowLanguage() {
const [language, setLanguage] = useState(navigator.language);
return (
<section>
<h1>Your language is {language}!</h1>
<button onClick={() => setLanguage("fr-FR")}>Je préfère le Français</button>
</section>
);
}