1 import { useCallback, useState } from 'react';
3 export default function useControlled<V>(controlled: V, defaultValue?: V) {
4 const isControlled = controlled !== undefined;
6 const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue);
8 const setValueIfUncontrolled = useCallback((v: V) => {
10 setUncontrolledValue(v);
14 const value = isControlled ? controlled : uncontrolledValue;
17 * type-cast here to ensure that this hook's return type is a tuple
18 * instead of an array as typescript seems to interpret it by default
20 return [value, setValueIfUncontrolled] as const;