@nex-ui/hooks
Version:
A collection of React Hooks for Nex UI components.
36 lines (33 loc) • 1.32 kB
JavaScript
"use client";
import { useState, useRef, useEffect } from 'react';
import { __DEV__, isFunction } from '@nex-ui/utils';
import { useEvent } from './useEvent.mjs';
function useControlledState(value, defaultValue, onChange) {
const [state, setState] = useState(value ?? defaultValue);
const controlled = value !== undefined;
const prevControlledRef = useRef(value !== undefined);
useEffect(()=>{
const prevControlled = prevControlledRef.current;
if (__DEV__ && prevControlled !== controlled) {
console.error(`Warning: A component changed from ${prevControlled ? 'controlled' : 'uncontrolled'} to ${controlled ? 'controlled' : 'uncontrolled'}.`);
}
prevControlledRef.current = controlled;
}, [
controlled
]);
const setValue = useEvent((newValue)=>{
if (isFunction(newValue)) {
console.error("Warning: useControlledState doesn't support function updates, which can cause unexpected behavior. https://github.com/facebook/react/issues/18178#issuecomment-595846312");
}
if (!controlled) {
setState(newValue);
}
onChange?.(newValue);
});
const currentValue = controlled ? value : state;
return [
currentValue,
setValue
];
}
export { useControlledState };