UNPKG

@redocly/theme

Version:

Shared UI components lib

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