Skip to content

Commit

Permalink
docs(visualization): add example of useSyncExternalStore
Browse files Browse the repository at this point in the history
  • Loading branch information
manudeli committed Aug 17, 2024
1 parent 5d3e26e commit 0720992
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions websites/visualization/src/app/react/useSyncExternalStore/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use client'
import React, { useState, useSyncExternalStore } from 'react'

export default function Page() {
const [store] = useState(new Store())
const state = useSyncExternalStore(
store.subscribe,
() => store.state,
() => store.state
)

console.log('render')

return (
<div>
<div>State: {state}</div>

<button onClick={() => store.set(1)}>1</button>
<button onClick={() => store.set(2)}>2</button>
<button onClick={() => store.set(3)}>3</button>
<button onClick={() => store.set(4)}>4</button>
</div>
)
}

class Subscribable<TListener extends (...args: any[]) => unknown> {
listeners = new Set<TListener>()
subscribe = (listener: TListener) => {
this.listeners.add(listener)
return () => this.listeners.delete(listener)
}
notify = () => this.listeners.forEach((listener) => listener())
}

class Store extends Subscribable<() => void> {
state = 0
set(num: number) {
this.state = num
this.notify()
}
}

0 comments on commit 0720992

Please sign in to comment.