onChange or onBlur to change the state in ReactJs?

Amruth L S picture Amruth L S · Sep 28, 2018 · Viewed 7.8k times · Source

//Assume am changing state in handleChange function.

In case of onChange event state will update every character change.

  <input
    type="text"
    name="name"
    onChange={this.handleChange}
    id="name"
  />

In case of onBlur event state will update at single shot after leaving input fields.

 <input
   type="text"
   name="name"
   onBlur={this.handleChange}
   id="name"
 />

which approach is best to update the state in React and why ?

Answer

alpay picture alpay · Sep 28, 2018

This is actually a trade-off decision.

I assume that, in your event handler function, you are calling React setState() to update your states.

A call to setState is asynchronous. It creates a "pending state transition." (See here for more details). It is really fast and has a reducer to update only changed nodes. So you really don't need to think about performance.

  • Choose onChange(): If you need the latest state immediately after input change, for example:

Search suggestion after each input (like Google search box)

Validating input after every change

  • Choose onBlur(): If you only need the latest state at the end of the final input, for example:

Every change triggers a fetch event that checks if entered username or email exists


Also think of this scenario:

The end-user filled all 3 registration inputs (name, password and email), but after the last input i.e. email, s/he directly clicked the send button (which has fired your signup method without the updated email value/state).

Since setState is asynchronous and has not updated the email state yet, you might face problems about null email inputs.

So, my unofficial suggestion is to use onChange whenever possible and use onBlur only when you need final changed value.