onChange or onBlur to change the state in ReactJs?

10,968

Solution 1

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.

Solution 2

You can choose either of methods based on your requirement.

For example, if you need to perform validations to a field while the input is being entered , you could choose onChange.

Setting the state with onChange would be called every-time you enter something to field which leads to re-render the input again.

onBlur would call the setState only when you focus-out the input.

In my Opinion, onBlur would be good option , but it totally depends on the requirement which we have.

Share:
10,968

Related videos on Youtube

Amruth
Author by

Amruth

Primary Skills JavaScript, ReactJs, Redux, HTML5 and CSS3. Secondary Skills NodeJs, ExpressJs, Java/J2EE, Springs Rest Apis and Hibernate Mysql and MongoDB. skype :- Lsamruth Few of my best answers. How to avoid adding prefix “unsafe” to link by Angular2? gatsby --version > -bash: gatsby: command not found TypeError: Object(…) is not a function reactjs Module not found: 'redux'

Updated on May 21, 2022

Comments

  • Amruth
    Amruth almost 2 years

    //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 ?