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, and pass the Unit to useUnit Hook to bind the Unit with your React component.

useUnit Hook:

TypeScript
JavaScript
1
import { useState, useEffect } from "react";
2
import { UnitBase } from "@activejs/core";
3
​
4
const bind = <T extends Function>(method: T, thisArg: any): T =>
5
method.bind(thisArg)
6
​
7
export type UnitValueType<T> = T extends UnitBase<infer X> ? X : never
8
​
9
export function useUnit<U extends UnitBase<any>>(unit: U) {
10
type T = UnitValueType<U>
11
const [value, setValue] = useState<T>()
12
​
13
useEffect(() => {
14
const subscription = unit.subscribe(setValue);
15
return () => subscription.unsubscribe();
16
}, [])
17
​
18
return {
19
value,
20
dispatch: bind(unit.dispatch, unit),
21
resetValue: bind(unit.resetValue, unit)
22
}
23
}
Copied!
1
import { useState, useEffect } from 'react'
2
import { UnitBase } from '@activejs/core'
3
​
4
export const useUnit = (unit) => {
5
const [value, setValue] = useState()
6
​
7
useEffect(() => {
8
const subscription = unit.subscribe(setValue)
9
return () => subscription.unsubscribe()
10
}, []);
11
​
12
const dispatch = v => unit.dispatch(v)
13
const resetValue = () => unit.resetValue()
14
​
15
return {value, dispatch, resetValue}
16
}
Copied!

Examples:

  • See this for basic usage.
Copy link