useControllableState
Controlled + uncontrolled component state pattern.
Import
TypeScript
import { useControllableState } from '@/hooks';API
Signature
useControllableState({ value?, defaultValue, onChange? })
When to use
Use useControllableState instead of re-implementing the same pattern in multiple components.
SSR / Next.js
Fully SSR-safe. Pure React state.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useControllableStateEditor
type Props = { value?: string; defaultValue?: string; onChange?: (v: string) => void }; function Input(props: Props) { const [value, setValue] = useControllableState({ value: props.value, defaultValue: props.defaultValue ?? '', onChange: props.onChange, }); return <input value={value} onChange={(e) => setValue(e.target.value)} />; }
Preview
Implementation source
Full library source for useControllableState — copy into your project when you are not installing a package yet.
hooks/state/useControllableState.ts
import { useCallback, useEffect, useRef, useState } from 'react';
export interface UseControllableStateOptions<T> {
value?: T;
defaultValue: T;
onChange?: (value: T) => void;
}
/**
* Supports controlled and uncontrolled usage patterns.
*/
export function useControllableState<T>({
value,
defaultValue,
onChange,
}: UseControllableStateOptions<T>): [T, (next: T | ((prev: T) => T)) => void] {
const isControlled = value !== undefined;
const [uncontrolled, setUncontrolled] = useState(defaultValue);
const current = isControlled ? (value as T) : uncontrolled;
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
const setValue = useCallback(
(next: T | ((prev: T) => T)) => {
const resolved =
typeof next === 'function' ? (next as (prev: T) => T)(current) : next;
if (!isControlled) {
setUncontrolled(resolved);
}
onChangeRef.current?.(resolved);
},
[current, isControlled],
);
// Keep uncontrolled in sync if defaultValue identity is intended to reseeds is rare; no-op.
useEffect(() => {
// Controlled mode does not keep local mirror.
}, [value]);
return [current, setValue];
}
Copy-paste example
useControllableState.example.tsx
'use client';
import { useControllableState } from '@/hooks';
type Props = { value?: string; defaultValue?: string; onChange?: (v: string) => void };
export function Input(props: Props) {
const [value, setValue] = useControllableState({
value: props.value,
defaultValue: props.defaultValue ?? '',
onChange: props.onChange,
});
return <input value={value} onChange={(e) => setValue(e.target.value)} />;
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Keep state setters stable; prefer action helpers over manual setState spreads.
- Source of truth: open
hooks/state/useControllableState.tsfor implementation details