import * as React from "react"; type UseControllableStateParams = { prop?: T | undefined; defaultProp?: T | undefined; onChange?: (state: T) => void; }; export function useUncontrolledState({ defaultProp, onChange, }: Omit, "prop">) { const uncontrolledState = React.useState(defaultProp); const [value] = uncontrolledState; const prevValueRef = React.useRef(value); const handleChange = useCallbackRef(onChange); React.useEffect(() => { if (prevValueRef.current !== value) { handleChange(value as T); prevValueRef.current = value; } }, [value, prevValueRef, handleChange]); return uncontrolledState; } /** * A custom hook that converts a callback to a ref to avoid triggering re-renders when passed as a * prop or avoid re-executing effects when passed as a dependency */ export function useCallbackRef any>( callback: T | undefined, ): T { const callbackRef = React.useRef(callback); React.useEffect(() => { callbackRef.current = callback; }); // https://github.com/facebook/react/issues/19240 return React.useMemo( () => ((...args) => callbackRef.current?.(...args)) as T, [], ); }