47 lines
1.1 KiB
Plaintext
47 lines
1.1 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[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>
|
|
);
|
|
}
|
|
----
|
|
|
|
=== Compliant solution
|
|
|
|
[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>
|
|
);
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
* https://reactjs.org/docs/hooks-state.html[hooks-state] - React API reference |