UNPKG

@matthew.ngo/reform

Version:

A flexible and powerful React form management library with advanced validation, state observation, and multi-group support

36 lines (32 loc) 1.12 kB
import { useCallback, useRef } from 'react'; /** * Hook to create a memoized callback that maintains reference equality * even when dependencies change, but only updates the function when * the result would be different. * * @param callback - The callback function to memoize * @param deps - Dependencies array for the callback * @returns Memoized callback function */ export function useMemoizedCallback<T extends (...args: any[]) => any>( callback: T, deps: React.DependencyList ): T { // Store the previous callback and deps const callbackRef = useRef<T>(callback); const depsRef = useRef<React.DependencyList>(deps); // Check if deps have changed in a way that would affect the callback const hasRelevantChanges = deps.some( (dep, i) => !Object.is(dep, depsRef.current[i]) ); // Update refs if there are relevant changes if (hasRelevantChanges) { callbackRef.current = callback; depsRef.current = deps; } // Return a stable callback that uses the latest implementation return useCallback( ((...args: any[]) => callbackRef.current(...args)) as T, [] ); }