import { useCallback, useState } from "react"; interface CommonControlledStateProps { value?: T; defaultValue?: T; } type UseControlledStateProps = CommonControlledStateProps & { onChange?: (value: T, ...args: Rest) => void; }; export function useControlledState( props: UseControlledStateProps, ): readonly [T, (next: T, ...args: Rest) => void] { const { value, defaultValue, onChange } = props; const isControlled = value !== undefined; const [internalState, setInternalState] = useState(value !== undefined ? value : (defaultValue as T)); const state = isControlled ? (value as T) : internalState; const setState = useCallback( (next: T, ...args: Rest) => { if (!isControlled) setInternalState(next); onChange?.(next, ...args); }, [isControlled, onChange], ); return [state, setState] as const; }