45 lines
1.1 KiB
Plaintext
45 lines
1.1 KiB
Plaintext
React's setState 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>
|
|
);
|
|
};
|
|
----
|
|
|
|
== See
|
|
|
|
* https://reactjs.org/docs/hooks-state.html[hooks-state] - React API reference |