# 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](/activejs/integrations/react/useunit-hook.md).&#x20;

### useObservable Hook:

{% tabs %}
{% tab title="TypeScript" %}

```typescript
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;
}
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
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;
}
```

{% endtab %}
{% endtabs %}

### Example:

```typescript
// 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:

* [StackBlitz](https://stackblitz.com/edit/react-ts-aj1f8t?file=index.tsx) example that shares a Unit among multiple components.
* Simple [Counter](https://docs.activejs.dev/integrations/react#3-counter-using-useobservable-hook) example.
* See [this](https://docs.activejs.dev/fundamentals/systems/asyncsystem#react) for usage in combination with [AsyncSystem](/activejs/fundamentals/systems/asyncsystem.md).


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.activejs.dev/activejs/integrations/react/useobservable-hook.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
