useObservable Hook
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 useUnit.

useObservable Hook:

TypeScript
JavaScript
1
import { useState, useEffect } from "react";
2
import { Observable } from "rxjs";
3
​
4
export type ObservableValueType<T> = T extends Observable<infer X> ? X : never;
5
​
6
export function useObservable<U extends Observable<any>>($: U) {
7
type T = ObservableValueType<U>;
8
const [value, setValue] = useState<T>();
9
​
10
useEffect(() => {
11
const subscription = $.subscribe(setValue);
12
return () => subscription.unsubscribe();
13
}, [$]);
14
​
15
return value;
16
}
Copied!
1
import { useState, useEffect } from "react";
2
import { Observable } from "rxjs";
3
​
4
export function useObservable(observable) {
5
const [value, setValue] = useState();
6
​
7
useEffect(() => {
8
const subscription = observable.subscribe(setValue);
9
return () => subscription.unsubscribe();
10
}, [observable]);
11
​
12
return value;
13
}
Copied!

Example:

1
// create a Unit or System, Cluster, Action
2
const listUnit = new ListUnit({initialValue: ['🀯']});
3
​
4
// a simple component
5
function Visualizer() {
6
const value = useObservable(listUnit);
7
​
8
return <span>{value}</span>;
9
}
10
​
11
// it'll render this immediately and will render any future values
12
🀯
Copied!

More Examples: