Last active
May 2, 2024 05:46
-
-
Save jonkwheeler/9eed8fd79dcd50edd3522c7695185a84 to your computer and use it in GitHub Desktop.
useState vs useSignal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { render } from "preact"; | |
import { useRef, useState } from "preact/hooks"; | |
import { signal, useSignal, useComputed } from "@preact/signals"; | |
// Create a signal that can be subscribed to: | |
const globalCount = signal(0); | |
function Counter({ number }) { | |
const [stateCount, setStateCount] = useState(0); | |
const renderCounter = useRef(0); | |
renderCounter.current = renderCounter.current + 1; | |
const localCount = useSignal(0); | |
const localCountDoubled = useComputed(() => localCount.value * 2); | |
const localCountTripled = useComputed(() => localCount.value * 3); | |
return ( | |
<div style={{ padding: 20, border: "solid 2px" }}> | |
<h4 style={{ color: "purple" }}>Component {number}</h4> | |
<p style={{ color: "red" }}> | |
Render Count: <h1>{renderCounter.current}</h1> | |
</p> | |
<div style={{ padding: 20, border: "solid 2px lightgray" }}> | |
<h3>React State (full re-render)</h3> | |
<button onClick={() => setStateCount((prev) => prev + 1)}> | |
stateCount + 1 | |
</button> | |
<p style={{ color: "red" }}>stateCount: {stateCount}</p> | |
</div> | |
<div style={{ padding: 20, border: "solid 2px lightgray" }}> | |
<h3>Signals (no Virtual DOM diff)</h3> | |
<button | |
onClick={() => { | |
localCount.value++; | |
}} | |
> | |
localCount + 1 | |
</button> | |
<p style={{ color: "green" }}>Count: {localCount}</p> | |
<p style={{ color: "green" }}>localCountDoubled: {localCountDoubled}</p> | |
<p style={{ color: "green" }}>localCountTripled: {localCountTripled}</p> | |
<hr style={{ marginBottom: 20, border: "solid 1px lightgray" }} /> | |
<button | |
onClick={() => { | |
globalCount.value++; | |
}} | |
> | |
globalCount + 1 | |
</button> | |
<p style={{ color: "blue" }}>globalCount: {globalCount}</p> | |
</div> | |
</div> | |
); | |
} | |
function App() { | |
return ( | |
<div style={{ display: "flex" }}> | |
<Counter number={1} /> | |
<Counter number={2} /> | |
</div> | |
); | |
} | |
render(<App />, document.getElementById("app")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment