useControllableValue
Unifies controlled and uncontrolled component state.
Unifies controlled and uncontrolled component state.
Import
import { useControllableValue } from '@kamod-ch/hooks'Live demo
Basic demo
Unifies controlled and uncontrolled component state.
Parent value: controlled
import { useState } from 'preact/hooks'
import { useControllableValue } from '@kamod-ch/hooks'
function DemoField(props: { value: string; onChange: (value: string) => void }) {
const [value, setValue] = useControllableValue(props)
return <input value={value} onInput={(event) => setValue(event.currentTarget.value)} />
}
export default function UseControllableValueDemo() {
const [value, setValue] = useState('controlled')
return (
<div>
<DemoField value={value} onChange={setValue} />
<p><strong>Parent value:</strong> {value}</p>
</div>
)
}
API
TypeScript signature
import type { SetStateAction } from '../utils/types-compat.js';
export interface Options<T> {
defaultValue?: T;
defaultValuePropName?: string;
valuePropName?: string;
trigger?: string;
}
export type Props = Record<string, any>;
export interface StandardProps<T> {
value: T;
defaultValue?: T;
onChange: (val: T) => void;
}
declare function useControllableValue<T = any>(props: StandardProps<T>): [T, (v: SetStateAction<T>) => void];
declare function useControllableValue<T = any>(props?: Props, options?: Options<T>): [T, (v: SetStateAction<T>, ...args: any[]) => void];
export default useControllableValue;
/SSR considerations
This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.
Browser compatibility
Works in any modern browser supported by Preact.