# useUnit Hook

Using the ActiveJS is similar to RxJS Observables and other observable and subscription-based libraries.

However, if you don't want to create a `useState` and `useEffect` binding every time you use a Unit, you can create a custom `Hook` for using ActiveJS [Units](/activejs/fundamentals/units.md), and pass the Unit to `useUnit` Hook to bind the Unit with your React component.

### useUnit Hook:

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

```typescript
import { useState, useEffect } from "react";
import { UnitBase } from "@activejs/core";

const bind = <T extends Function>(method: T, thisArg: any): T =>
  method.bind(thisArg)

export type UnitValueType<T> = T extends UnitBase<infer X> ? X : never

export function useUnit<U extends UnitBase<any>>(unit: U) {
  type T = UnitValueType<U>
  const [value, setValue] = useState<T>()

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

  return {
    value,
    dispatch: bind(unit.dispatch, unit),
    resetValue: bind(unit.resetValue, unit)
  }
}
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import { useState, useEffect } from 'react'
import { UnitBase } from '@activejs/core'

export const useUnit = (unit) => {
  const [value, setValue] = useState()

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

  const dispatch = v => unit.dispatch(v)
  const resetValue = () => unit.resetValue()

  return {value, dispatch, resetValue}
}
```

{% endtab %}
{% endtabs %}

### Examples:

* See [this](https://docs.activejs.dev/integrations/react#2-counter-using-useunit-hook) for basic usage.


---

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