-
Notifications
You must be signed in to change notification settings - Fork 0
Example React Hooks
Ivan Kasenkov edited this page Aug 31, 2021
·
9 revisions
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.lastValue ?? null,
);
useLayoutEffect(() => {
next(stream.lastValue ?? null); // observable value may change beetween 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.value,
);
useLayoutEffect(() => s.subscribe({ next }).unsubscribe, [s]);
return value;
};