useLegacyStore.tsx 764 B

1234567891011121314151617181920212223242526272829
  1. import {useCallback, useSyncExternalStore} from 'react';
  2. import type {Store} from 'reflux';
  3. interface LegacyStoreShape extends Pick<Store, 'listen'> {
  4. getState(): any;
  5. }
  6. /**
  7. * Returns the state of a reflux store. Automatically unsubscribes when destroyed
  8. *
  9. * ```tsx
  10. * const teams = useLegacyStore(TeamStore);
  11. * ```
  12. *
  13. * @link https://react.dev/reference/react/useSyncExternalStore
  14. */
  15. export function useLegacyStore<T extends LegacyStoreShape>(
  16. store: T
  17. ): ReturnType<T['getState']> {
  18. const listener = useCallback(
  19. (fn: () => void) => {
  20. // Pass undefined to 2nd listen argument otherwise it explodes
  21. return store.listen(fn, undefined) as () => void;
  22. },
  23. [store]
  24. );
  25. return useSyncExternalStore(listener, store.getState);
  26. }