When handling an onChange
event, this one works:
<input type="file" onChange={this.onChange}
Not this one, that executes instantaneously the function:
<input type="file" onChange={this.onChange()}
Not this other one, doesn't execute:
<input type="file" onChange={() => this.onChange}
But this one does:
<input type="file" onChange={() => this.onChange()}
But, while the first one automatically sends the event object, the second one needs to explicitly send it:
<input type="file" onChange={(e) => this.onChange(e)}
onChange(e) {
console.log(e.target.files[0])
}
Why is that? and when should we use one or the another?
With onChange={(e) => this.onChange(e)}
, you are essentially creating a new function that calls this.onChange method during each render.
With onChange={this.onChange}
, you are directly accessing this.onChange method. This method is only defined once and is used multiple times. Basically, you are avoiding creating a new function with a new render thus giving the application a slight performance enhancement