From 0720992b968527c669ecd76889cb8a8ff287187d Mon Sep 17 00:00:00 2001 From: Jonghyeon Ko Date: Sat, 17 Aug 2024 16:53:43 +0900 Subject: [PATCH] docs(visualization): add example of useSyncExternalStore --- .../app/react/useSyncExternalStore/page.tsx | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 websites/visualization/src/app/react/useSyncExternalStore/page.tsx diff --git a/websites/visualization/src/app/react/useSyncExternalStore/page.tsx b/websites/visualization/src/app/react/useSyncExternalStore/page.tsx new file mode 100644 index 000000000..051129924 --- /dev/null +++ b/websites/visualization/src/app/react/useSyncExternalStore/page.tsx @@ -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 ( +
+
State: {state}
+ + + + + +
+ ) +} + +class Subscribable unknown> { + listeners = new Set() + 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() + } +}