49 lines
1.6 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
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.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
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.
[source,javascript,diff-id=1,diff-type=compliant]
----
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>
);
}
----
== Resources
=== Documentation
* React Documentation - https://react.dev/reference/react[React Hooks]
* React Documentation - https://react.dev/reference/react/useState[useState - API reference]
* React Documentation - https://react.dev/reference/react/useState#im-getting-an-error-too-many-re-renders[useState - Troubleshooting]