Skip to content

Example React Hooks

Ivan Kasenkov edited this page Mar 27, 2023 · 9 revisions

React 18

Codesandbox Demo

React 18 introduced new hook useSyncExternalStore for external stores:

const value = useSyncExternalStore(
  (next) => stream.subscribe({ next }).unsubscribe,
  stream.snapshot
);

React 17

Codesandbox Demo

useStream.ts

import { Stream } from '@keiii/k-stream';
import { Reducer, useLayoutEffect, useReducer } from 'react';

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

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

  return value;
};

useBehaviourSubject.ts

import { BehaviourSubject } from '@keiii/k-stream';
import { Reducer, useLayoutEffect, useReducer } from 'react';

export const useBehaviourSubject = <T>(s: BehaviourSubject<T>): T => {
  const [value, next] = useReducer<Reducer<T, T>>(
    (_, action) => action,
    s.getValue(),
  );

  useLayoutEffect(() => s.subscribe({ next }).unsubscribe, [s]);

  return value;
};
Clone this wiki locally