Is there a way to use setInterval with preact signals in order to render a component?

188 Views Asked by At

I would like to achieve this behavior using signals:

useEffect(() => {
  const interval = setInterval(() => {
    console.log('This will run every second!');
  }, 1000);
  return () => clearInterval(interval);
}, []);

Do I need to compute first and then use effect according to their documentation? source: https://preactjs.com/guide/v10/signals/

Any tip will be appreciated, thanks.

1

There are 1 best solutions below

4
On BEST ANSWER

There is no need to use compute here, you can go ahead and use effect. Count signal will be updated everytime interval fires.

import { signal, effect } from "@preact/signals";

const count = signal(0);

function Counter() {
  effect(() => {
    const intervalId = setInterval(() => {
      count.value ++;
    }, 1000);

    return () => {
      clearInterval(intervalId);
    };
  });

  return <div>{count}</div>;
}