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;

Answer

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.