Skip to content

Effect Service API

createEffectService()

Create a service that encapsulates logic to perform an effect in response to dependency changes.

It utilizes EffectProcessor under the hood.

ts
function createEffectService(effectProcessor: EffectProcessor): EffectService

Parameters:

ParameterTypeRequiredDescription
effectProcessorEffectProcessorYesThe processor that manages, tracks, and triggers effects.

Returns: EffectService

ts
interface EffectService {
  useEffect: UseEffect;
}

service.useEffect()

  • Type: UseEffect

Perform an effect in response to dependency changes.

The effect's reactivity can be configured through its dependency specification:

  • No array (undefined): The effect always runs when triggered.
  • Empty array ([]): The effect runs only once.
  • Array with values ([a, b]): The effect runs when triggered and any listed value changes.

This method calls the trackEffect method of the processor.

ts
type UseEffect = (
  effect: () => unknown,
  depsFn?: () => unknown[],
  options?: UseEffectOptions,
) => () => void
ParameterTypeRequiredDescription
effect() => unknownYesThe function that performs the effect. If the return value is a function, it will be called before each effect re-run as the cleanup function.
depsFn() => unknown[]NoThe function that resolves the effect's dependency values.
optionsUseEffectOptionsNoOptions to configure the effect's execution behavior.

Returns: A function to toggle the active state of the effect.

UseEffectOptions

ts
interface UseEffectOptions {
  immediate?: boolean;
  sync?: boolean;
  once?: boolean;
}
PropertyTypeDescription
immediatebooleanWhether to run the effect immediately on setup.
Default: true
syncbooleanWhether to run the effect synchronously.
Default: false
oncebooleanWhether to run the effect only once.
Default: false

Released under the MIT License.