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

205
Views
Why does the setEmotion function get printed each time I click on a button?

There is only one console log statement and I am not calling App() each time (from what I know). Why is the console log statement ran each time a button is pressed?

import './App.css';
import React, {useState} from "react";

function App() {
  const [emotion, setEmotion] = useState("happy");
  console.log(emotion, setEmotion)
  return(
    <>
   <h1>Current emotion is {emotion}</h1>
   <button onClick={() => setEmotion("sad")}>Sad</button>
   <button onClick={() => setEmotion("angry")}>Angry</button>
   <button onClick={() => setEmotion("happy")}>Happy</button>
    </>
  )
}

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

0

The console.log is executed each time because you're updating the component's state on each button click.

You've created a function component App which executes itself whenever it needs to be (re-)rendered. That render happens whenever any of its state (in this case emotion) was updated, which in turn happens when clicking any of the buttons.

The reason emotion doesn't reset on each render is that React internally keeps track of its value and it will only update emotion whenever setEmotion is called. The initial value of "happy" is only considered on the first render.

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!