Skip to main content

useTargetEffect

This hook is similar to React.useEffect, but it has one more targets parameter as another dependency list. targets can be functions, refs, or any other type values. If targets are functions or refs, this hook will get their return values or reference values, and compare these values with the previous dependencies. It is useful when using DOM nodes as effect dependencies.

API

function useTargetEffect(
effect: React.EffectCallback,
deps: React.DependencyList,
targets: ReadonlyArray<EffectTarget<any>>
): void;

type Nullable<T> = T | undefined | null;
type EffectTarget<T> =
| Nullable<T>
| (() => Nullable<T>)
| { current: Nullable<T> };

Example

import React, { useRef } from "react";
import { useTargetEffect } from "@lilib/hooks";

function Example() {
const domRef = useRef<HTMLDivElement>(null);

useTargetEffect(
() => {
// Do something.
},
[],
[domRef]
);

return <div ref={domRef}>...</div>;
}