Skip to content

Example React Hooks

Ivan Kasenkov edited this page Sep 13, 2026 · 14 revisions

React 18+

React 18 introduced new hook useSyncExternalStore for external stores:

export function useStream<T>(stream: BehaviourSubject<T>): T;
export function useStream<T>(stream: Stream<T>): T | null;
export function useStream<T>(stream: Stream<T>): T | null {
  return useSyncExternalStore(
    useCallback(
      (onStoreChange) => stream.subscribe({ next: onStoreChange }).unsubscribe,
      [stream],
    ),
    stream.snapshot,
    stream.snapshot,
  );
}

React 17

export function useStream<T>(stream: BehaviourSubject<T>): T;
export function useStream<T>(stream: Stream<T>): T | null;
export function useStream<T>(stream: Stream<T>): T | null {
  const [value, next] = useReducer(
    (_, action) => action,
    stream.snapshot()
  );

  useLayoutEffect(() => {
    next(stream.snapshot()); // observable value may change between render and value commit
    return stream.subscribe({ next }).unsubscribe;
  }, [stream, next]);

  return value;
}

Clone this wiki locally