useSyncedState
useState that updates to the new value when the initial state changes.
Try changing the initial value above. The synced state will update automatically. You can also edit the synced state directly, and it will maintain your changes until the initial value changes.
View source
A hook that behaves like useState, but automatically syncs the local state when the initial value changes. This is useful when you need local state that can be modified by the user, but should also update when the source value changes from a parent component or prop.
Features
- Automatically syncs local state when initial value changes
- Maintains local modifications until initial value updates
- Same API as
useStatefor easy migration - Type-safe with full TypeScript support
use-synced-state.ts
1import { useEffect, useState } from 'react';2
3/**4 * Just like a useState, but if the initial state is changed, the state will be updated to the new value.5 * @important — You should only ever use this hook if you need to use the setter, otherwise you should just useMemo the value you want to sync.6 */7const useSyncedState = <T>(initialState: T) => {8 const [state, setState] = useState<T>(initialState);9
10 useEffect(() => {11 setState(initialState);12 }, [initialState]);13
14 return [state, setState] as const;15};16
17export default useSyncedState;