This library was built on top of React's useState hook that allows to ease partial state updates
import { usePartialState } from 'use-partial-state';
type ComplexObject = { index: number; value: string };
const initialValue: ComplexObject = { index: 1, value: 'initial value' };
const newValue: ComplexObject = { index: 2, value: 'new value' };
const partialUpdate: Partial<ComplexObject> = { value: 'updated value' };
const [complexObject, setComplexObject, updateComplexObject] = usePartialState<ComplexObject>(initialValue);
console.log(complexObject);
// { index: 1, value: 'initial value' }
setComplexObject(newValue);
console.log(complexObject);
// { index: 2, value: 'new value' }
updateComplexObject(partialUpdate);
console.log(complexObject);
// { index: 2, value: 'updated value' }
If the initialValue
or previous state is undefined then partial update value will be used as final one:
import { usePartialState } from 'use-partial-state';
type ComplexObject = { index: number; value: string };
const partialUpdate: Partial<ComplexObject> = { value: 'updated value' };
const [complexObject, setComplexObject, updateComplexObject] = usePartialState<ComplexObject>();
updateComplexObject(partialUpdate);
console.log(complexObject);
// { value: 'updated value' }