DEV Community

Damian Diego
Damian Diego

Posted on

#Devdoubt-React

Hello devs! I hope you are doing well.

I came across this piece of code from chakra UI, and I'm trying to understand what is the point of doing this or in which cases is it useful?

export function useCallbackRef<T extends (...args: any[]) => any>(
    callback: T | undefined,
    deps: DependencyList = []
) {
    const callbackRef = useRef(callback)

    useEffect(() => {
        callbackRef.current = callback
    })

    // eslint-disable-next-line react-hooks/exhaustive-deps
    return useCallback(((...args) => callbackRef.current?.(...args)) as T, deps)
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
brense profile image
Rense Bakker

I don't see how it is useful... It looks like someone went a bit overboard trying to optimize rerenders, but i don't see a functional difference between this and just using useCallback in the first place... Probably someone was consuming a callback function from somewhere, that was changing every render and they wrote this hook to remedy the situation. What they should have done is just put the original callback into a useCallback hook...