48 lines
1.4 KiB
JavaScript
48 lines
1.4 KiB
JavaScript
// packages/react/use-controllable-state/src/useControllableState.tsx
|
|
import * as React from "react";
|
|
import { useCallbackRef } from "@radix-ui/react-use-callback-ref";
|
|
function useControllableState({
|
|
prop,
|
|
defaultProp,
|
|
onChange = () => {
|
|
}
|
|
}) {
|
|
const [uncontrolledProp, setUncontrolledProp] = useUncontrolledState({ defaultProp, onChange });
|
|
const isControlled = prop !== void 0;
|
|
const value = isControlled ? prop : uncontrolledProp;
|
|
const handleChange = useCallbackRef(onChange);
|
|
const setValue = React.useCallback(
|
|
(nextValue) => {
|
|
if (isControlled) {
|
|
const setter = nextValue;
|
|
const value2 = typeof nextValue === "function" ? setter(prop) : nextValue;
|
|
if (value2 !== prop) handleChange(value2);
|
|
} else {
|
|
setUncontrolledProp(nextValue);
|
|
}
|
|
},
|
|
[isControlled, prop, setUncontrolledProp, handleChange]
|
|
);
|
|
return [value, setValue];
|
|
}
|
|
function useUncontrolledState({
|
|
defaultProp,
|
|
onChange
|
|
}) {
|
|
const uncontrolledState = React.useState(defaultProp);
|
|
const [value] = uncontrolledState;
|
|
const prevValueRef = React.useRef(value);
|
|
const handleChange = useCallbackRef(onChange);
|
|
React.useEffect(() => {
|
|
if (prevValueRef.current !== value) {
|
|
handleChange(value);
|
|
prevValueRef.current = value;
|
|
}
|
|
}, [value, prevValueRef, handleChange]);
|
|
return uncontrolledState;
|
|
}
|
|
export {
|
|
useControllableState
|
|
};
|
|
//# sourceMappingURL=index.mjs.map
|