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

145
Views
onClick function is called for every input change

Im trying to post to a local server using an onclick function, but every time the input field changes here, it calls the function, leading to unecessary function calls, and I can't figure out why it is being called here.

const testPost = () => {
  console.log("Clicked!")
  Axios.post('http://localhost:3001/', {testName: "albumName"})
    .then(() => {
      console.log('successful insert')
    });
};

function App() {

  const [albumName, setAlbumName] = useState('')

  return (
    <div className="App">
        <input type="text" name="albumName" onChange={(e) => {
          setAlbumName(e.target.value)
        }}/>
        <button onClick={testPost()}>Submit</button>
      </header>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Lose the (), So it’s just {testPost}.

If you do testPost() you’re calling/executing testPost every time the component renders. As soon as that line is encountered by the JS interpreter, it runs the function.

With onClick, you only want to pass the reference of the function to be called on click. So just use testPost.

Also with react, every time the state changes within a component, it re-renders the whole component, so that’s why your function is being called every time there is an input change.

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!