|
| 1 | +import * as React from 'react'; |
| 2 | + |
| 3 | +export default function useControlledState<T, R = T>( |
| 4 | + defaultStateValue: T | (() => T), |
| 5 | + option?: { |
| 6 | + defaultValue?: T | (() => T); |
| 7 | + value?: T; |
| 8 | + onChange?: (value: T, prevValue: T) => void; |
| 9 | + postState?: (value: T) => T; |
| 10 | + }, |
| 11 | +): [R, (value: T) => void] { |
| 12 | + const { defaultValue, value, onChange, postState } = option || {}; |
| 13 | + const [innerValue, setInnerValue] = React.useState<T>(() => { |
| 14 | + if (value !== undefined) { |
| 15 | + return value; |
| 16 | + } |
| 17 | + if (defaultValue !== undefined) { |
| 18 | + return typeof defaultValue === 'function' |
| 19 | + ? (defaultValue as any)() |
| 20 | + : defaultValue; |
| 21 | + } |
| 22 | + return typeof defaultStateValue === 'function' |
| 23 | + ? (defaultStateValue as any)() |
| 24 | + : defaultStateValue; |
| 25 | + }); |
| 26 | + |
| 27 | + let mergedValue = value !== undefined ? value : innerValue; |
| 28 | + if (postState) { |
| 29 | + mergedValue = postState(mergedValue); |
| 30 | + } |
| 31 | + |
| 32 | + function triggerChange(newValue: T) { |
| 33 | + setInnerValue(newValue); |
| 34 | + if (mergedValue !== newValue && onChange) { |
| 35 | + onChange(newValue, mergedValue); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return [(mergedValue as unknown) as R, triggerChange]; |
| 40 | +} |
0 commit comments