LogoLogo
  • Introduction
  • Intro
    • 🚀Getting Started
    • Key Characteristics
    • Fundamentals
    • Motivation
  • Fundamentals
    • 💾Units
      • BoolUnit
      • NumUnit
      • StringUnit
      • DictUnit
      • ListUnit
      • GenericUnit
    • 🤝Systems
      • AsyncSystem
      • Custom AsyncSystem
    • 🤜Action
    • 📦Cluster
  • 🔨Utilities
    • Stream
    • Selection
  • Integrations
    • Angular
    • React
      • useObservable Hook
      • useUnit Hook
  • 📖Guides
    • Configuration
    • Nesting
    • Events
    • Typings
    • Caching
    • Persistence
    • Immutability
    • Freeze and Mute
    • Development Environment
    • General Guidelines
  • More
    • 👀Examples
    • ✍️Articles
Powered by GitBook
On this page
  • useObservable Hook:
  • Example:
  • More Examples:

Was this helpful?

  1. Integrations
  2. React

useObservable Hook

PreviousReactNextuseUnit Hook

Last updated 4 years ago

Was this helpful?

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;
}
import { useState, useEffect } from "react";
import { Observable } from "rxjs";

export function useObservable(observable) {
  const [value, setValue] = useState();

  useEffect(() => {
    const subscription = observable.subscribe(setValue);
    return () => subscription.unsubscribe();
  }, [observable]);

  return value;
}

Example:

// 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.

Simple example.

See for usage in combination with .

useUnit
StackBlitz
Counter
this
AsyncSystem