import { Dispatch, SetStateAction, useCallback, useState } from 'react'; interface UseControlledUncontrolledProps { value?: T; defaultValue?: T; onChange?: Dispatch>; } export function useControlledUncontrolled({ value, defaultValue, onChange }: UseControlledUncontrolledProps): [T, Dispatch>, boolean] { const [internalValue, setInternalValue] = useState(defaultValue); const handleChange: Dispatch> = useCallback( (val: T) => { setInternalValue(val); onChange?.(val); }, [onChange], ); // Controlled mode if (value !== undefined) { return [value as T, onChange, true]; } // Uncontrolled mode return [internalValue as T, handleChange, false]; }