In the useState hook the setItems runs every time when the page is refreshed and sets the same items again. Can t=you help me with this, please.
useEffect(() => {
if (inputArr.length > 0) {
window.localStorage.setItem("inputArr", JSON.stringify(inputArr));
console.log("set", inputArr);
}
}, [inputArr]);
2
Answers
Here you are in a useEffect hook, not a useState hook.
That’s why setItem is triggered every page refreshing at first, and it will be triggered again if [inputArr] is changed.
While using
useEffect()
hook it is called once at start and then every time when the variable in the dependency array updates. i.e[inputArr]
in your case.Whenever the
inputArr
will have any changes theuseEffect
hook will be called. If you don’t want it to be called multiple times , just keep the dependency array empty that’s it.Feel free to ask me if you have any doubts. You can also get more info from official documentation Official documentation link to useEffect