All files / src/utils/subscribe subscribe.ts

100% Statements 6/6
100% Branches 0/0
100% Functions 2/2
100% Lines 4/4

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 275x                                         5x 17x   17x    
import { Watch } from 'watch-state'
 
/**
 * Stable subscribe factory for `useSyncExternalStore` with watch-state.
 * Creates a `Watch` instance that calls the provided callback on state changes.
 *
 * @description
 * Memoized outside components to prevent recreation on every render.
 * Ensures React reuses the same subscription reference across re-renders.
 * Automatically cleans up with `watcher.destroy()` on unsubscribe.
 *
 * @example
 * ```ts
 * const state = new State(0)
 * const value = useSyncExternalStore(subscribe, () => state.value)
 * // same `useWatch(state)`
 * ```
 *
 * @param callback - Function to call when watch-state notifies changes
 * @returns Cleanup function that destroys the Watch instance
 */
export const subscribe = (callback: () => void) => {
  const watcher = new Watch(callback)
 
  return () => watcher.destroy()
}