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
?
F
For many input fields it is difficult to handle the form state on your own so you may use Redux Form it handles the state on it own.
See this link https://redux-form.com/7.4.2/examples/simple/
anyway onBlur would be a best practice in handling form input state because onChange may set the state whenever the a change is made in input field for example if you type "name" in input field it sets state for 4 times so the page may re render 4 times,But on onBlur after the focus is out of input field the state is set.
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 :)
onChange. I wouldnt try to over-optimize the re-renders you're seeing unless it is something actually noticeable to an end-user. Usually isnt an issue unless you have larger forms. Typically when working with forms in React, you use controlled fields where react maintains the state and passes the value back down into the field (see https://reactjs.org/docs/forms.html#controlled-components), in which case it really only makes sense to use onChange for maintaining the state value.
If you do end up needing to optimize further, you can split up parts of your form into separate components that use PureComponent or shouldComponentUpdate to prevent those parts of the form from re-rendering unnecessarily.