1.0.1 • Published 4 years ago
react-use-value-change v1.0.1
Install
$ npm install react-use-value-change --saveor
$ yarn add react-use-value-changeThe problem
Quite often I find myself having complex useEffect to detect the state changes. This library helps to keep up state tracking.
It contains Three simplified methods:
useStringValueChangeuseNumberValueChangeuseBooleanValueChange
Simple setup
const [currentValue, {setValue, resetValue, resetToCurrentValue, resetToOriginalValue}, {equals, original}] = useStringValueChange("the initial value");currentValueis the string current valueoriginalis immutable original value (until value is reset)equalsindicates iforiginal === currentValuesetValue("new value")will change thecurrentValue, keepsoriginalandequalsis false if the new value is different form originalresetValue()will resetoriginaltocurrentValueandequalsto trueresetValue("something else")will resetcurrentValueandoriginalto "something else" andequalsto trueresetToCurrentValue()will reset theoriginaltocurrentValueandequalsto trueresetToOriginalValue()will reset thecurrentValuetooriginalandequalsto true
All the other methods follows the same pattern.
Using react input
The difference are with input listeners
useStringInputValueChangeacceptsHTMLTextAreaElement | HTMLInputElementuseNumberInputValueChangeacceptsHTMLInputElement (input type number)useBooleanInputValueChangeacceptsHTMLInputElement (checkbox or radio)
Those accept HTMLTextAreaElement | HTMLInputElement as setters. Which means one has to call
setValue(value: HTMLInputElement) instead of setValue(value: string) (or boolean or number)
a bit more...
There is also an umbrella method for more complex logic: useValueChange, which has to be approached carefully as it might trigger recursive rendering.
See useValueChange.test.ts how to use it.
Might be a bug, but it is not
When is used the initial value is immutable. One has to use the React useffect to reset the value.