UNPKG

stream-chat-react

Version:

React components to create chat conversations or livestream style chat

40 lines (39 loc) 1.71 kB
import { useCallback, useMemo } from 'react'; import { useSyncExternalStore } from 'use-sync-external-store/shim'; // eslint-disable-next-line @typescript-eslint/no-empty-function const noop = () => { }; export function useStateStore(store, selector) { const wrappedSubscription = useCallback((onStoreChange) => { const unsubscribe = store?.subscribeWithSelector(selector, onStoreChange); return unsubscribe ?? noop; }, [store, selector]); const wrappedSnapshot = useMemo(() => { let cachedTuple; return () => { const currentValue = store?.getLatestValue(); if (!currentValue) return undefined; // store value hasn't changed, no need to compare individual values if (cachedTuple && cachedTuple[0] === currentValue) { return cachedTuple[1]; } const newlySelected = selector(currentValue); // store value changed but selected values wouldn't have to, double-check selected if (cachedTuple) { let selectededAreEqualToCached = true; for (const key in cachedTuple[1]) { if (cachedTuple[1][key] === newlySelected[key]) continue; selectededAreEqualToCached = false; break; } if (selectededAreEqualToCached) return cachedTuple[1]; } cachedTuple = [currentValue, newlySelected]; return cachedTuple[1]; }; }, [store, selector]); const state = useSyncExternalStore(wrappedSubscription, wrappedSnapshot); return state; }