import React from "react";

export const myUseSyncExternalStore = () => {
  if (!React.useSyncExternalStore) {
    React.useSyncExternalStore = function (subscribe, getSnapshot, getServerSnapshot) {
      const [snapshot, setSnapshot] = React.useState(() => getSnapshot());
      // 订阅更新
      React.useEffect(() => {
        const checkUpdate = () => {
          const currentSnapshot = getSnapshot();
          setSnapshot(currentSnapshot);
        };

        const unsubscribe = subscribe(checkUpdate);
        checkUpdate(); // 立即检查一次

        return () => {
          if (unsubscribe) {
            unsubscribe();
          }
        };
      }, [subscribe, getSnapshot]);

      return snapshot;
    };
  }
};
