Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
Event handlers, render and other methods binding in React

Why do event handlers need to bind with the constructor while render and other methods do not require the same in react?

You may see here in the below code that for handlesubmit I need to bind it with the constructor but I don't need to do the same with api method. Can someone explain to me the reason behind it?

Thank you

class App extends Component{
constructor (props){ 
    super(props);

  this.state={
    users:[],
    loading:false
  };
  this.handleSubmit = this.handleSubmit.bind(this); 
}

api(){ 
  this.setState({
    loading: true
  }) 
    axios('https://api.randomuser.me/')
  .then(respond => this.setState({ 
    users: [...this.state.users, ...respond.data.results], 
    loading: false
  }))
}
handleSubmit(e){ 
  e.preventDefault(); 
  this.api();
}

UNSAFE_componentWillMount(){
this.api();
}

render(){
let {loading,users} = this.state; 
console.log("run")
return <div className = "App"> 
 <form onSubmit = {this.handleSubmit}> 
  <input type="submit" value= "Refresh" /> 
  </form>
{!loading 
  ? (users.map( user => 
  <div key = {user.id.value}> 
  <h2> {user.name.first} </h2>
  <p>{user.email}</p>
  </div>
)) : (<Loading/>)} 
</div>;
}
}

export default App;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

So that their references don't change on each re-render.

  this.handleSubmit = this.handleSubmit.bind(this); 

You can just use arrow function

handleSubmit = (e) => { 
  e.preventDefault(); 
  this.api();
}

why do you need to bind a function in a constructor

See more https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

https://www.freecodecamp.org/news/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb/

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!