Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React onChange handler is being called multiple times during page load

We're trying to add a onChange handler to one of our custom components - namely, a Checkbox component (the only reason for it being a custom component is so that we can efficiently encapsulate the intermediate HTML attribute). It looks something like this:

<Checkbox
  id="select-all"
  onChange={this.handleSelectAllChange(ids)}
  indeterminate={isIndeterminate}
  checked={areVisibleItemsSelected}
  disabled={isDisabled}
/>

The handler function is structured somewhat like this:

handleSelectAllChange(ids) {
  // omitted code that filters on ids and produces newIds

  this.props.updateIds(newIds);
}

Where this.props.updateIds is a passed-down function that modifies the parent component's state.

The problem is that this function is called about 10 times during page load, which is not intended. I thought it was only called when the actual checkbox element is modified?

like image 993
Penny Avatar asked May 17 '17 08:05

Penny


People also ask

Why is my function being called twice in React?

Its because your app component is a wrap in StrictMode . It is expected that setState updaters will run twice in strict mode in development. This helps ensure the code doesn't rely on them running a single time (which wouldn't be the case if an async render was aborted and later restarted).

Why useEffect is calling multiple times?

Your useEffect is executed only once per render cycle, but you have several state updates in your useEffect which cause a re-render. Hence you get a lot of alerts. useEffect executes on every re-render if you don't pass the dependency array.

How do you handle onChange in React JS?

How to use handleChange() function in react component? An onChange event is triggered when values are entered in the input. This fires a function handleChange(), that is used to set a new state for the input.


2 Answers

By declaring it like this onChange={this.handleSelectAllChange(ids)} the method call happens immediately at rendering the CheckBox. With ES6 you can avoid this by using

onChange={() => this.handleSelectAllChange(ids)}

This means you pass a new function which will call handleSelectAllChange on change.

like image 112
Murat Karagöz Avatar answered Oct 04 '22 18:10

Murat Karagöz


I just had the same issue... I was able to fix the problem stopping the propagation of the event. Add this in the function being called by your onChange event:

e.stopPropagation();

like image 29
rii Avatar answered Oct 04 '22 16:10

rii