4.2 how the functions of the components are execute

Reacting to events is a great first step, but how do we actually change what appears on the screen? Let's say we want the h2 title of an expense to be updated when the user clicks the button. A first instinct is to introduce a plain JavaScript variable inside the component.

const ExpenseItem = (props) => {
  let title = props.title;

  const clickHandler = () => {
    title = 'Updated!';
    console.log(title);
  };

  return (
    /* ... */
    <h2>{title}</h2>
    <button onClick={clickHandler}>Change title</button>
  );
};

Why this does not work as expected

  • You can click the button as many times as you want — the new value is logged in the console, proving the handler runs.
  • However, the h2 on screen never changes: it keeps displaying the original title.
  • The reason is that React only re-runs the component function when the application is first rendered. It does not re-execute it just because a regular variable has been mutated.

So the click handler is called every time, but React does not know that something visible should change, so the UI stays frozen. This is exactly the limitation that the state concept is going to fix: by telling React explicitly "this value is part of my state", we will make sure the component re-runs and the screen reflects the new value. We will cover this in detail in the next lesson — see you there.