I'm building a custom hook that accepts a function. If the function will not change between re-renders/updates, where should I memoize the function?
OPTION 1
const useCustomHook = (callback) => {
const callbackRef = useRef();
callbackRef.current = callback;
// No effect, this will be re-created every time this hook is called
// because a new instance of callback is being passed
const callbackWrapper = useCallback(() => {
if (callbackRef.current) {
callbackRef.current();
}
}, [callbackRef]);
// use callbackWrapper
}
const Component = () => {
// New instance of passed callback will be created each time this component re-renders
useCustomHook(() => {
console.log(`I'm being passed to the hook`);
});
// ...
// ...
return <div></div>;
}
OPTION 2
const useCustomHook = (callback) => {
// Callback is already memoized
const callbackRef = useRef();
callbackRef.current = callback;
// use callbackRef
}
const Component = () => {
// Memoized function passed, but
// 1. Is this allowed?
// 2. Requires more effort by users of the hook
useCustomHook(useCallback(() => {
console.log(`I'm being passed to the hook`);
}, []));
// ...
// ...
return <div></div>;
}
Option 2 seems more valid but it requires users of the custom hook to first enclose their function in a useCallback() hook. Is there an alternative way where users don't need to enclose the passed function in useCallback()?