skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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 the useEffect hook will be called. If you don’t want it to be called multiple times , just keep the dependency array empty that’s it.

    useEffect(() => {
        if (inputArr.length > 0) {
          window.localStorage.setItem("inputArr", JSON.stringify(inputArr));
          console.log("set", inputArr);
        }
      }, []);
    

    Feel free to ask me if you have any doubts. You can also get more info from official documentation Official documentation link to useEffect

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search