@trellixio/roaster-coffee
Version:
Beans' product component library
38 lines (37 loc) • 1.74 kB
JavaScript
import { useState } from 'react';
/**
* A custom React hook that provides a value, a function to update the value, and a flag that indicates whether the value is controlled or not.
* This hook is designed to provide a flexible input component that can be controlled or uncontrolled.
*
* @typeParam T - The type of the input value.
* @param value - The value of the input for a controlled component.
* @param defaultValue - The initial value of the input for an uncontrolled component.
* @param finalValue - The final value of the input for an uncontrolled component when `value` and `defaultValue` are not provided.
* @param onChange - The callback function that is called when the input value changes in a controlled component.
* @returns A tuple containing the input value, a function to update the input value, and a flag that indicates whether the input value is controlled.
*
* @example
* ```tsx
* function MyInput({ value, onChange }) {
* const [inputValue, setInputValue, isControlled] = useUncontrolled({ value, onChange });
*
* return (
* <input
* value={isControlled ? value : inputValue}
* onChange={(e) => setInputValue(e.target.value)}
* />
* );
* }
*```
*/
export function useUncontrolled({ value, defaultValue, finalValue, onChange = () => { }, }) {
const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue !== undefined ? defaultValue : finalValue);
const handleUncontrolledChange = (val) => {
setUncontrolledValue(val);
onChange === null || onChange === void 0 ? void 0 : onChange(val);
};
if (value !== undefined) {
return [value, onChange, true];
}
return [uncontrolledValue, handleUncontrolledChange, false];
}