1 | import { useState } from "react";
|
2 |
|
3 | export 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 | */
|
17 | export 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 | }
|