|
| 1 | +# Install |
| 2 | + |
| 3 | +``` |
| 4 | +$ npm install react-use-value-change --save |
| 5 | +``` |
| 6 | +or |
| 7 | +``` |
| 8 | +$ yarn add react-use-value-change |
| 9 | +``` |
| 10 | + |
| 11 | +[Direct link to npmjs.com](https://www.npmjs.com/package/react-use-value-change) |
| 12 | + |
| 13 | +# The problem |
| 14 | + |
| 15 | +Quite often I find myself having complex useEffect to detect the state changes. This library helps to keep up state tracking. |
| 16 | + |
| 17 | +It contains Three simplified methods: |
| 18 | + |
| 19 | +- `useStringValueChange` |
| 20 | +- `useNumberValueChange` |
| 21 | +- `useBooleanValueChange` |
| 22 | + |
| 23 | +## Simple setup |
| 24 | + |
| 25 | +```typescript |
| 26 | +const [currentValue, {setValue, resetValue, resetToCurrentValue, resetToOriginalValue}, {equals, original}] = useStringValueChange("the initial value"); |
| 27 | +``` |
| 28 | +- `currentValue` is the string current value |
| 29 | +- `original` is immutable original value (until value is reset) |
| 30 | +- `equals` indicates if `original === currentValue` |
| 31 | +- `setValue("new value")` will change the `currentValue`, keeps `original` and `equals` is false if the new value is different form original |
| 32 | +- `resetValue()` will reset `original` to `currentValue` and `equals` to true |
| 33 | +- `resetValue("something else")` will reset `currentValue` and `original` to "something else" and `equals` to true |
| 34 | +- `resetToCurrentValue()` will reset the `original` to `currentValue` and `equals` to true |
| 35 | +- `resetToOriginalValue()` will reset the `currentValue` to `original` and `equals` to true |
| 36 | + |
| 37 | +All the other methods follows the same pattern. |
| 38 | + |
| 39 | +## Using react input |
| 40 | + |
| 41 | +The difference are with input listeners |
| 42 | + |
| 43 | +- `useStringInputValueChange` accepts `HTMLTextAreaElement | HTMLInputElement` |
| 44 | +- `useNumberInputValueChange` accepts `HTMLInputElement (input type number)` |
| 45 | +- `useBooleanInputValueChange` accepts `HTMLInputElement (checkbox or radio)` |
| 46 | + |
| 47 | +Those accept `HTMLTextAreaElement | HTMLInputElement` as setters. Which means one has to call |
| 48 | + |
| 49 | +`setValue(value: HTMLInputElement)` instead of `setValue(value: string)` (or boolean or number) |
| 50 | + |
| 51 | +## a bit more... |
| 52 | + |
| 53 | +There is also an umbrella method for more complex logic: `useValueChange`, which has to be approached carefully as it might trigger recursive rendering. |
| 54 | + |
| 55 | +See [useValueChange.test.ts](https://github.com/dustinest/typescript-async-utils/tree/main/react-usevalue/src/lib/useValueChange.test.ts) how to use it. |
| 56 | + |
| 57 | + |
| 58 | +## Might be a bug, but it is not |
| 59 | + |
| 60 | +When is used the initial value is immutable. One has to use the React `useffect` to reset the value. |
0 commit comments