How to Avoid Re-rendering Caused by Callback Function Props
In React, when passing a function as component props, one needs to be careful with managing references
to avoid unnecessary re-renders.
Although most case we use useCallback
to prevent unnecessary re-renders, I found an alternative solution sharing.
The code that inspired this article is radix-ui/primitives's useCallbackRef.
This article will discuss the use cases and logic of useCallbackRef
.
Below is the useCallbackRef
code we are going to discuss.
Can you guess in what situations it might be used?
// useCallbackRef.js
import { useRef, useEffect, useMemo } from 'react';
export function useCallbackRef(callback) {
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
});
return useMemo(() => ((...args) => callbackRef.current?.(...args)), []);
}