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
  • useUnit Hook:
  • Examples:

Was this helpful?

  1. Integrations
  2. React

useUnit Hook

PrevioususeObservable HookNextConfiguration

Last updated 4 years ago

Was this helpful?

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

useUnit Hook:

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)
  }
}
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}
}

Examples:

See for basic usage.

Units
this