# 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](https://docs.activejs.dev/activejs/fundamentals/units), 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.
