UNPKG

845 BPlain TextView Raw
1import { useState } from "react";
2
3export type DispatchStateAction<T> = React.Dispatch<React.SetStateAction<T>>;
4
5/**
6 * A helper hook for handling controlled and uncontrolled values in a
7 * component's props.
8 *
9 * If the value is uncontrolled, pass `undefined` as `controlledValue` and use
10 * the returned setter to update it.
11 *
12 * If the value is controlled, pass the controlled value as the second argument,
13 * which will always be returned as `value`.
14 *
15 * @template T - The type of the value.
16 */
17export function useControlledValue<T>(
18 defaultValue: T,
19 controlledValue: T | undefined
20): [T, DispatchStateAction<T>] {
21 const [uncontrolledValue, setValue] = useState(defaultValue);
22
23 const value =
24 controlledValue === undefined ? uncontrolledValue : controlledValue;
25
26 return [value, setValue] as [T, DispatchStateAction<T>];
27}