Since all the fundamental constructs like Units, Actions, Systems, and Clusters are Observable, it makes sense that we create a custom Hook to easily bind their value to a component's local state. useObservable is much simpler and ergonomic to use than .
useObservable Hook:
import { useState, useEffect } from "react";
import { Observable } from "rxjs";
export type ObservableValueType<T> = T extends Observable<infer X> ? X : never;
export function useObservable<U extends Observable<any>>($: U) {
type T = ObservableValueType<U>;
const [value, setValue] = useState<T>();
useEffect(() => {
const subscription = $.subscribe(setValue);
return () => subscription.unsubscribe();
}, [$]);
return value;
}
// create a Unit or System, Cluster, Action
const listUnit = new ListUnit({initialValue: ['🤯']});
// a simple component
function Visualizer() {
const value = useObservable(listUnit);
return <span>{value}</span>;
}
// it'll render this immediately and will render any future values
🤯
More Examples:
example that shares a Unit among multiple components.