react-use-value-change
v1.0.1
Published
React value change listener
Downloads
3
Maintainers
Readme
Install
$ npm install react-use-value-change --save
or
$ yarn add react-use-value-change
The 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:
useStringValueChange
useNumberValueChange
useBooleanValueChange
Simple setup
const [currentValue, {setValue, resetValue, resetToCurrentValue, resetToOriginalValue}, {equals, original}] = useStringValueChange("the initial value");
currentValue
is the string current valueoriginal
is immutable original value (until value is reset)equals
indicates iforiginal === currentValue
setValue("new value")
will change thecurrentValue
, keepsoriginal
andequals
is false if the new value is different form originalresetValue()
will resetoriginal
tocurrentValue
andequals
to trueresetValue("something else")
will resetcurrentValue
andoriginal
to "something else" andequals
to trueresetToCurrentValue()
will reset theoriginal
tocurrentValue
andequals
to trueresetToOriginalValue()
will reset thecurrentValue
tooriginal
andequals
to true
All the other methods follows the same pattern.
Using react input
The difference are with input listeners
useStringInputValueChange
acceptsHTMLTextAreaElement | HTMLInputElement
useNumberInputValueChange
acceptsHTMLInputElement (input type number)
useBooleanInputValueChange
acceptsHTMLInputElement (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.