The problem is that the useEffect runs twice, but the Strict Mode is off, can you please help with that?
useEffect(() => {
console.log("useEffect is running");
try {
const itemsArr = window.localStorage.getItem("inputArr");
const storedItems = itemsArr ? JSON.parse(itemsArr) : [];
setInputArr(storedItems);
console.log("getItem result:", itemsArr);
} catch (error) {
console.error("Failed to parse inputArr from localStorage:", error);
setInputArr([]);
}
}, []);
useEffect(() => {
if (inputArr.length > 0) {
window.localStorage.setItem("inputArr", JSON.stringify(inputArr));
console.log("set", inputArr);
}
}, [inputArr]);
user27452169 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
When the first useEffect connects for the first time, setInputArr is updated.
Let’s refer to the following useEffectf to change inputArr to the dependent array. Because of this, useEffect is executed twice because inputArr is updated with setInputArr.
Let’s explain in more depth!
-
The rendering of useEffect varies depending on how the dependencies are arranged.
-
If the array is empty, once the page is rendered, it will not be rendered again.
-
However, as shown above, if there is a value in the dependency array, it is rendered when the value is updated.
2