Files
Folo/packages/internal/hooks/src/useControlled.ts
T
Innei 4d746522f1 refactor: remove unused files and clean up project structure
- Deleted obsolete configuration files and unused components across various packages.
- Updated package.json files to reflect the removal of dependencies.
- Cleaned up code by removing unnecessary exports and unused imports in multiple modules.

Signed-off-by: Innei <tukon479@gmail.com>
2025-04-28 20:58:51 +08:00

26 lines
687 B
TypeScript

import { useCallback, useState } from "react"
import { useRefValue } from "./useRefValue"
export const useControlled = <T>(
value: T | undefined,
defaultValue: T,
onChange?: (v: T, ...args: any[]) => void,
): [T, (value: T) => void] => {
const [stateValue, setStateValue] = useState(value !== undefined ? value : defaultValue)
const isControlled = value !== undefined
const onChangeRef = useRefValue(onChange)
const setValue = useCallback(
(newValue: T) => {
if (!isControlled) {
setStateValue(newValue)
}
onChangeRef.current?.(newValue)
},
[isControlled, onChangeRef],
)
return [isControlled ? value : stateValue, setValue]
}