0

I want to add a value in one of my state variables every second and show it on UI. I am trying the below code, but I am seeing weird behavior on UI(UI element is not updating every second correctly). I think because set state is async, it is taking time to update the state which is causing weird behavior. How can I achieve this?

const [abc, setAbc] = useState("");
  const xyz = "aaa";
  useEffect(() => {
    setInterval(() => {
      setAbc((prev) =>
        prev.length !== xyz.length ? prev + xyz[prev.length] : ""
      );
    }, 1000);
  });

user11823877
  • 143
  • 1
  • 15
  • Can u increase the interval time to just check if its the issue with async setstate – Neel Dsouza Sep 13 '21 at 13:03
  • Your solution will be similar to [this answer](https://stackoverflow.com/a/57542337/5963874). In summary, you will need to keep track of the interval id and clear it in the `useEffect` cleanup. You also need to add an array of dependencies to your `useEffect`, even if it's just `[]` so that it only runs on render. – Robert Corponoi Sep 13 '21 at 13:09
  • Does this answer your question? [How to setInterval for every 5 second render with React hook useEffect in React Native app?](https://stackoverflow.com/questions/57542264/how-to-setinterval-for-every-5-second-render-with-react-hook-useeffect-in-react) – Robert Corponoi Sep 13 '21 at 13:10
  • I tried adding clearinterval in the use effect. That is not working. Also, I tried increasing interval time, It is working as expected in that case. – user11823877 Sep 13 '21 at 13:17

0 Answers0