Created
July 27, 2025 22:15
-
-
Save gvergnaud/9be08c5869720b631da995d1947f311c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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