import * as React from 'react'; type UseAutoControlledOptions = { defaultValue: Value; value: Value; initialValue?: Value; }; const isUndefined = (value: any) => typeof value === 'undefined'; /** * Returns a stateful value, and a function to update it. Mimics the `useState()` React Hook * signature. */ export const useAutoControlled = ( options: UseAutoControlledOptions, ): [Value, React.Dispatch>] => { const { defaultValue, initialValue = undefined, value } = options; const [state, setState] = React.useState(isUndefined(defaultValue) ? (initialValue as Value) : defaultValue); return [isUndefined(value) ? state : value, setState]; };