Introduction to Component State
Introduction to Component State
1. Why Props Aren't Enough
Props allow a parent component to pass data down to its children. However, props are read-only. If an application only had props, user interfaces would remain completely static and unresponsive to user actions.
Modern web applications require dynamic interactions:
- Submitting a form and showing a validation spinner
- Toggling a dropdown menu open or closed
- Incrementing an e-commerce shopping cart quantity
- Filtering a searchable list of courses as the user types
To remember values across user interactions and re-render the screen when those values change, React components use State.
2. What is State?
State is a component's private, internal memory. Unlike regular local variables that reset to their initial values every time a function executes, state variables persist in memory across component re-renders.
Whenever a state variable changes, React automatically schedules a re-render of that component. The component function re-executes, generates a fresh Virtual DOM representation with the updated state, and reconciles the real DOM to match.
3. Why Regular Variables Fail for Interactivity
Consider this intuitive attempt using a standard JavaScript local variable:
Why does this fail?
- 1Local variables do not trigger renders: React has no way of knowing that
countchanged. Mutating a local variable does not notify React to re-render. - 2Local variables do not survive renders: Even if another event forced the component to re-render, the function would re-execute from line 1, resetting
let count = 0back to zero!
4. The Solution: React State
To make a component interactive:
- 1Retain the data between renders.
- 2Trigger React to re-render the component with the new data.
React provides the useState hook to achieve both requirements simultaneously.
Practice Quiz
let count = 0; count++;) fail to update the UI on the screen?<Counter /> are rendered on a page, how do their states behave?The useState Hook Fundamentals
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Passing Children and Composing Components | The useState Hook Fundamentals |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.