Skip to content

Instantly share code, notes, and snippets.

@gvergnaud
Created July 27, 2025 22:15
Show Gist options
  • Save gvergnaud/9be08c5869720b631da995d1947f311c to your computer and use it in GitHub Desktop.
Save gvergnaud/9be08c5869720b631da995d1947f311c to your computer and use it in GitHub Desktop.
import React from "react";
/**
* Hook to run effects related to a dom element.
* Unlike useEffect, this hooks returns a ref callback.
* The effect will be run every time the element changes.
*/
const useElementEffect = <T extends HTMLElement>(
callback: (el: T) => (() => void) | undefined | void,
deps: React.DependencyList,
): React.RefCallback<T> => {
// eslint-disable-next-line react-hooks/exhaustive-deps
const memoedCallback = React.useCallback(callback, deps);
const unmountRef = React.useRef<(() => void) | undefined | void>(undefined);
return React.useCallback(
(node) => {
if (node) {
unmountRef.current?.();
unmountRef.current = memoedCallback(node);
} else {
unmountRef.current?.();
unmountRef.current = undefined;
}
},
[memoedCallback],
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment