Liu Song’s Projects


~/Projects/fre

git clone https://code.lsong.org/fre

Commit

Commit
bc91e9008b2e1cf3324e71b6c622edbf41a545cb
Author
changhaozhao <[email protected]>
Date
2021-12-08 16:52:24 +0800 +0800
Diffstat
 demo/src/use-sync-external-store.tsx | 39 ++++++++++++++++++++++++++++++
 package.json | 2 

add use-sync-external-store


diff --git a/demo/src/use-sync-external-store.tsx b/demo/src/use-sync-external-store.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..e135621ebb41f3d41d3b579182b173b65f7693ba
--- /dev/null
+++ b/demo/src/use-sync-external-store.tsx
@@ -0,0 +1,39 @@
+import { useState, useEffect, useLayoutEffect } from '../../src'
+
+export function useSyncExternalStore(subscribe, getSnapshot) {
+  const value = getSnapshot()
+  const [{ inst }, forceUpdate] = useState({ inst: { value, getSnapshot } })
+  useLayoutEffect(() => {
+    inst.value = value
+    inst.getSnapshot = getSnapshot
+
+    if (checkIfSnapshotChanged(inst)) {
+      forceUpdate({ inst })
+    }
+  }, [subscribe, value, getSnapshot])
+
+  useEffect(() => {
+    if (checkIfSnapshotChanged(inst)) {
+      forceUpdate({ inst })
+    }
+    const handleStoreChange = () => {
+      if (checkIfSnapshotChanged(inst)) {
+        forceUpdate({ inst })
+      }
+    }
+    return subscribe(handleStoreChange)
+  }, [subscribe])
+
+  return value
+}
+
+function checkIfSnapshotChanged(inst) {
+  const latestGetSnapshot = inst.getSnapshot
+  const prevValue = inst.value
+  try {
+    const nextValue = latestGetSnapshot()
+    return !Object.is(prevValue, nextValue)
+  } catch (error) {
+    return true
+  }
+}




diff --git a/package.json b/package.json
index 71f4d1cdd492f6931f29aa6fe28f207b4b14bca6..cbdba69976003101f453d4e90155d3c6444c2cf6 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
 {
   "name": "fre",
-  "version": "2.4.3",
+  "version": "2.4.4",
   "type": "module",
   "main": "dist/fre.js",
   "unpkg": "dist/fre.umd.js",