useSyncState
@guoba-ai/hook / useSyncState
Function: useSyncState()
function useSyncState<T>(prop, comparator?): [T, Dispatch<SetStateAction<T>>];Defined in: useSyncState.ts:30
A custom React hook that synchronizes the state with the prop.
Parameters
prop
T
The prop to synchronize with the state.
comparator?
(pre, cur) => boolean
Compare current and previous prop value, return true if they are identical.
Returns
[T, Dispatch<SetStateAction<T>>]
A state variable, and a function to update it.
Example
const [state, setState] = useSyncState(initialProp)
// state starts with initialProp
const [draft, setDraft] = useSyncState(user)
setDraft({ ...draft, name: 'Local edit' })
// The next different user prop replaces draft
const [selected, setSelected] = useSyncState(option, (prev, next) => prev.id === next.id)
// A new option object with the same id does not reset selectedWarning
Local state is overwritten when prop changes according to comparator. If the comparator returns true, local edits are kept.