import { useState, useCallback } from 'react'; export function useControlledState( initialState: T, controlledValue?: T, ): [T, (newValue: T) => void] { const [state, setState] = useState(initialState); const isControlled = controlledValue !== undefined; const value = isControlled ? controlledValue : state; const setValue = useCallback( (newValue: T) => { if (!isControlled) { setState(newValue); } }, [isControlled], ); return [value, setValue]; }