useSyncedState
Local draft state that reseeds when props change.
Import
TypeScript
import { useSyncedState } from '@/hooks';API
Signature
useSyncedState<T>(source, isEqual?) → [state, setState]
When to use
Use useSyncedState 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 · useSyncedStateEditor
function EditableTitle({ title }: { title: string }) { const [draft, setDraft] = useSyncedState(title); return <input value={draft} onChange={(e) => setDraft(e.target.value)} />; }
Preview
Implementation source
Full library source for useSyncedState — copy into your project when you are not installing a package yet.
hooks/state/useSyncedState.ts
import {
useEffect,
useRef,
useState,
type Dispatch,
type SetStateAction,
} from 'react';
/**
* State that reseeds when the external source value changes.
* Useful for props-driven local drafts.
*/
export function useSyncedState<T>(
source: T,
isEqual: (a: T, b: T) => boolean = Object.is,
): [T, Dispatch<SetStateAction<T>>] {
const [state, setState] = useState(source);
const prevSource = useRef(source);
useEffect(() => {
if (!isEqual(prevSource.current, source)) {
prevSource.current = source;
setState(source);
}
}, [source, isEqual]);
return [state, setState];
}
Copy-paste example
useSyncedState.example.tsx
'use client';
import { useSyncedState } from '@/hooks';
export function EditableTitle({ title }: { title: string }) {
const [draft, setDraft] = useSyncedState(title);
return <input value={draft} onChange={(e) => setDraft(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/useSyncedState.tsfor implementation details