refactor: replace useState() with useSignal() (#1234)
This commit is contained in:
@@ -31,7 +31,8 @@ Here is an example of an island component that counts down to a specific time.
|
||||
```tsx
|
||||
// islands/Countdown.tsx
|
||||
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
import { useSignal } from "@preact/signals";
|
||||
import { useEffect } from "preact/hooks";
|
||||
|
||||
const timeFmt = new Intl.RelativeTimeFormat("en-US");
|
||||
|
||||
@@ -39,18 +40,16 @@ const timeFmt = new Intl.RelativeTimeFormat("en-US");
|
||||
// props to island components need to be JSON (de)serializable.
|
||||
export default function Countdown(props: { target: string }) {
|
||||
const target = new Date(props.target);
|
||||
const [now, setNow] = useState(new Date());
|
||||
const now = useSignal(new Date());
|
||||
|
||||
// Set up an interval to update the `now` date every second with the current
|
||||
// date as long as the component is mounted.
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
setNow((now) => {
|
||||
if (now > target) {
|
||||
clearInterval(timer);
|
||||
}
|
||||
return new Date();
|
||||
});
|
||||
if (now.value > target) {
|
||||
clearInterval(timer);
|
||||
}
|
||||
now.value = new Date();
|
||||
}, 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, [props.target]);
|
||||
|
||||
Reference in New Issue
Block a user