2023-05-03 11:06:20 +02:00
== Why is this an issue?
2022-07-22 12:11:14 +02:00
React's useState hook setter function should not be called directly in the body of a component, otherwise it would produce an infinite render loop. This can happen by mistake. Most commonly, the setter function is called from an event handler.
2022-07-22 11:38:46 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2022-07-22 11:38:46 +02:00
[source,javascript]
----
import { useState } from "react";
function ShowLanguage() {
const [language, setLanguage] = useState("fr-FR");
// Makes an infinite loop
setLanguage(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
=== Compliant solution
2022-07-22 11:38:46 +02:00
[source,javascript]
----
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
2022-07-22 11:38:46 +02:00
* https://reactjs.org/docs/hooks-state.html[hooks-state] - React API reference