2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-06-30 13:29:28 +02:00
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.
2022-07-22 11:38:46 +02:00
2023-06-30 13:29:28 +02:00
The loop "state updates -> triggers re-render -> state updates -> triggers re-render -> ..." will continue indefinitely.
2022-07-22 11:38:46 +02:00
2023-06-30 13:29:28 +02:00
[source,javascript,diff-id=1,diff-type=noncompliant]
2022-07-22 11:38:46 +02:00
----
import { useState } from "react";
function ShowLanguage() {
const [language, setLanguage] = useState("fr-FR");
2023-06-30 13:29:28 +02:00
setLanguage(navigator.language); // Noncompliant: causes an infinite loop
2022-07-22 11:38:46 +02:00
return (
<section>
<h1>Your language is {language}!</h1>
2023-06-30 13:29:28 +02:00
<button onClick={() => setLanguage("fr-FR")}>Je préfère le français</button>
2022-07-22 11:38:46 +02:00
</section>
);
2023-01-12 15:59:13 +01:00
}
2022-07-22 11:38:46 +02:00
----
2023-06-30 13:29:28 +02:00
Instead, the setter function should be called from an event handler.
2022-07-22 11:38:46 +02:00
2023-06-30 13:29:28 +02:00
[source,javascript,diff-id=1,diff-type=compliant]
2022-07-22 11:38:46 +02:00
----
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>
);
2023-01-12 15:59:13 +01:00
}
2022-07-22 11:38:46 +02:00
----
2023-05-03 11:06:20 +02:00
== Resources
2023-06-30 13:29:28 +02:00
=== Documentation
2022-07-22 11:38:46 +02:00
2023-10-19 11:46:59 +02:00
* 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]