refactor: replace useState() with useSignal() (#1234)

This commit is contained in:
Asher Gomez
2023-06-02 06:43:01 +10:00
committed by GitHub
parent 7b35cb07d4
commit 8fa4141e06
15 changed files with 120 additions and 112 deletions
+3 -4
View File
@@ -14,15 +14,14 @@ island. The file must have a default export that is a regular Preact component.
```tsx
// islands/MyIsland.tsx
import { useState } from "preact/hooks";
import type { Signal } from "@preact/signals";
export default function MyIsland() {
const [count, setCount] = useState(0);
const count = useSignal(0);
return (
<div>
Counter is at {count}.{" "}
<button onClick={() => setCount(count + 1)}>+</button>
Counter is at {count}. <button onClick={() => count.value += 1}>+</button>
</div>
);
}
+7 -8
View File
@@ -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]);