All files / src/hooks/useObservable useObservable.ts

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

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 27 28 29 30 31 32 33 34 35 36    5x                                                           5x 138x    
import type { Observable } from 'watch-state'
 
import { useSelector } from '../useSelector'
 
/**
 * React hook to subscribe a component to changes in a **watch-state** `Observable`.
 *
 * @description
 * Uses `useSyncExternalStore` for correct synchronization of external stores with React.
 * Automatically subscribes via `Watch` and unsubscribes on unmount.
 * React automatically optimizes re-renders — component only updates when the `snapshot` actually changes
 * (compared using `Object.is`).
 *
 * @example
 * ```ts
 * const $count = new State(42)
 *
 * const increase = () => {
 *   $count.value++
 * }
 *
 * const Button = () => {
 *   const num = useObservable($count)
 *
 *   return <button onClick={increase}>{num}</button>
 * }
 * ```
 *
 * @param state - **watch-state** `Observable`
 * @returns Current state value. Re-render occurs only when value actually changes.
 * @template T The type of the state value
 */
export function useObservable<T> (state: Observable<T>): T {
  return useSelector(() => state.value)
}