@baseplate-dev/ui-components
Version:
Shared UI component library
27 lines • 1.29 kB
JavaScript
import { useCallback, useEffect, useRef, useState } from 'react';
export function useControlledState(value, setValue, defaultValue) {
const isControlled = value !== undefined;
const isControlledRef = useRef(isControlled);
const setValuePropsRef = useRef(setValue);
const [internalState, setInternalState] = useState(defaultValue);
useEffect(() => {
if (process.env.NODE_ENV !== 'production' &&
isControlledRef.current !== isControlled) {
console.warn('Component is changing from controlled to uncontrolled (or visa versa). Component should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled Combobox for the lifetime of the component. Check the `value` prop.');
}
isControlledRef.current = isControlled;
}, [isControlled]);
useEffect(() => {
setValuePropsRef.current = setValue;
}, [setValue]);
const setState = useCallback((value) => {
if (setValuePropsRef.current) {
setValuePropsRef.current(value);
}
if (!isControlledRef.current) {
setInternalState(value);
}
}, []);
return [(isControlled ? value : internalState), setState];
}
//# sourceMappingURL=use-controlled-state.js.map