Course contentsShow
← React
Lesson 351 of 2,39610. useState BasicsFree lesson

Debugging Re-renders with console.log

Use strategic console.log placement to track when your component renders and what state it sees.

Debugging Re-renders with console.log

What you'll learn: How to use console.log strategically to see when your component renders and what state values it has at that moment.

The Debugging Challenge

When you call setState, React schedules a re-render, but you can't see it happen. State updates are asynchronous, and reading state right after setState shows the old value. So how do you actually see what's happening?

Your Best Friend: console.log at the Top

Place a console.log at the very top of your component function (outside any event handlers):

function Counter() {
  const [count, setCount] = useState(0);
  
  console.log('Counter rendered, count is:', count);
  
  const handleClick = () => {
    setCount(count + 1);
    console.log('Inside handler, count is still:', count); // old value!
  };
  
  return <button onClick={handleClick}>{count}</button>;
}

What You'll See

When you click the button:

  1. First log: "Inside handler, count is still: 0" (state hasn't updated yet)
  2. Then React re-renders
  3. Second log: "Counter rendered, count is: 1" (now the component sees new state)

Why This Works

Think of your component function like a security camera that takes a snapshot. The console.log at the top captures exactly what the component sees during that render. Each time React calls your function, you get a fresh snapshot with the current state values.

This technique reveals:

  • How many times your component renders
  • What state values exist during each render
  • Whether state changes actually triggered re-renders

Key Takeaway: Place console.log at the top of your component (not inside handlers) to track renders and see the state values React is working with during each render cycle.