I am working on a form with about 6 text input fields.
To save the values to my state, is it better to do so onBlur
or onChange
?
For example with onChange,
onChangeTextInput = ({ name, value }) => {
this.setState(state => ({
...state,
form: {
...state.form,
[name]: value
}
}));
};
Each time a key is pressed it will update the state. When I use the react tools "show update" I see a ton of updates because of how many times the field is updated.
Should I use onBlur instead to avoid this? Or is there a way to "batch" the state update?
Thanks
So it depends what you want the scenario to be :)
OnBlur will only trigger once the user clicks out of the field, if that isn't the correct user experience for you, my suggestion would be to use an input delay (also known as debouncing)! very cool once you get it dialed in nicely.
I won't give you the code outright because it's a really useful tool to understand properly in the future but check out:
import {debounce} from 'throttle-debounce';
There are many packages like this once, but what it does is set's a timeout on a function in your constructor:
this._updateValues = debounce(500, this._updateValues);
Every time this function is called it will wait 500 milliseconds before running, but if it is called again within that time frame, the timer will be reset :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With