4.4 a deeper look at the crochet useStat
In this short lesson we take a closer look at the useState hook by adding a simple console.log to observe when our component function actually runs. Just below the const [title, setTitle] = useState(props.title); declaration, drop the following statement:
const [title, setTitle] = useState(props.title);
console.log('ExpenseItem evaluated by React');
The log sits at the top level of the component, before the return statement. That means it executes every time the component function is called by React — that is, every time the component is rendered or re-rendered.
Observing the log in DevTools
- Open your browser's developer tools with F12 and switch to the Console tab.
- Reload the page: you should see "ExpenseItem evaluated by React" printed once for each expense item in the list.
- Click the Change Title button on any expense card.
- A new log line appears in the console, and the title on that card updates to "Updated!".
This visually confirms how useState works: calling setTitle tells React that the state of this specific component has changed, so React re-evaluates that component, the console.log fires again, and the JSX is re-rendered with the new value. See you in the next lesson where we keep digging into hooks.
Summary
This lesson demonstrates how to use React's useState hook effectively by combining console.log debugging with browser DevTools. You'll learn to verify that state changes work correctly by logging state values and observing them in the browser console when triggered by user interactions like clicking a 'Change Title' button.
Key points
- Use console.log() to output state values inside your component for debugging purposes
- Open browser DevTools (F12) to inspect console output and verify React's state evaluation
- Test state changes by triggering them through user interactions (button clicks) and observing the logs
- Console logs help confirm that state updates are firing and working as expected
FAQ
How do I verify that useState is working correctly in my component?
Add a console.log() statement inside your component to print the state values, then open your browser's DevTools (F12) and check the console output. When you interact with elements that trigger state changes (like clicking a button), you'll see new logs confirming the state has updated.
Why should I use the browser DevTools console when debugging React state?
The browser console shows you all console.log outputs in real-time, allowing you to track how your state changes with each user interaction. This visual feedback helps you understand if and when your useState hook is executing correctly.