mirror of
https://github.com/nextui-org/nextui.git
synced 2025-12-08 19:26:11 +00:00
28 lines
719 B
TypeScript
28 lines
719 B
TypeScript
/**
|
|
* Part of this code is taken from @chakra-ui/system ❤️
|
|
*/
|
|
|
|
import {useCallback, useRef} from "react";
|
|
import {useSafeLayoutEffect} from "@nextui-org/use-safe-layout-effect";
|
|
|
|
/**
|
|
* React hook to persist any value between renders,
|
|
* but keeps it up-to-date if it changes.
|
|
*
|
|
* @param fn the function to persist
|
|
* @param deps the function dependency list
|
|
*/
|
|
export function useCallbackRef<T extends (...args: any[]) => any>(
|
|
fn: T | undefined,
|
|
deps: React.DependencyList = [],
|
|
): T {
|
|
const ref = useRef(fn);
|
|
|
|
useSafeLayoutEffect(() => {
|
|
ref.current = fn;
|
|
});
|
|
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
return useCallback(((...args) => ref.current?.(...args)) as T, deps);
|
|
}
|