-
Notifications
You must be signed in to change notification settings - Fork 0
Example React Hooks
Ivan Kasenkov edited this page Sep 24, 2021
·
9 revisions
https://codesandbox.io/s/elastic-lederberg-wwymc
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;
};