function useDebounce(callback, delay) {
// Using the useRef allows us to avoid any re-renders when the callback changes
const callbackRef = React.useRef(callback)
// The useLayoutEffect will be run before any other code, so that
// we will have always latest callback function called in the debounce
// payload function.
React.useLayoutEffect(() => {
callbackRef.current = callback
})
return React.useMemo(
() => debounce((...args) => callbackRef.current(...args), delay),
[delay],
)
}
https://reactjs.org/docs/refs-and-the-dom.html#callback-refs
function SomeComponent() {
const [container, setContainer] = React.useState(null)
React.useEffect(() => {
if (!container) {
return
}
// do something with the container (DOM element)
}, [container])
return (<div ref={node => setContainer(node)}>content</div>)
}