Home > Software design >  Reactjs - How to add 1 item to array per second by using Hook useEffect and setInterval
Reactjs - How to add 1 item to array per second by using Hook useEffect and setInterval

Time:12-01

/**
   * init array: [1, 2]
   * Expect
   * array per 1s: [1, 2, 3]
   * array per 2s: [1, 2, 3, 4]
   * array per (n)s: [1, 2, 3, 4, ..., n]
   */
  const [countList, setCountList] = useState([]);
  const counter = useRef(0);
  useEffect(() => {
    const interval = setInterval(() => {
      counter.current = counter.current   1;
      setCountList([...countList, counter.current]);
    }, 1000);
    return () => clearInterval(interval);
  });

  return (
    <>
      <div>{countList.map((count) => count   ',')}</div>
    </>
  );

I want every second, the array to push 1 item and then display that on UI but the array only updates the last item. Exp [1, 2] => [1, 3] => [1, 4] ...

CodePudding user response:

Try this.

You have to regenerate the interval when countList was updated.

  const [countList, setCountList] = React.useState([]);
  const counter = React.useRef(0);

  React.useEffect(() => {
    const interval = setInterval(() => {
      counter.current = counter.current   1;

      setCountList([...countList, counter.current]);
    }, 1000);

    return () => clearInterval(interval);
  }, [countList]);

CodePudding user response:

The right way to do this would be to just set the interval once on mount, not set and clear it repeatedly. Sort of defeats the purpose of setting an interval. You need to use a callback function to get the previous value, and pass an empty dependency array to useEffect

  useEffect(() => {
    const interval = setInterval(() => {
      counter.current = counter.current   1;
      setCountList((prev) => [...prev, counter.current]);
    }, 1000);
    return () => clearInterval(interval);
  }, []);

demo: https://stackblitz.com/edit/react-ts-1rt29v?file=App.tsx

  • Related