The useState Hook Fundamentals
The useState Hook Fundamentals
1. Introducing useState
The useState hook is the fundamental tool for introducing local state into a React functional component. It is imported directly from the 'react' package.
2. Anatomy of useState
When you call useState, you pass the initial state value as an argument. It returns an array containing exactly two items:
- 1The State Variable (
state): The current value of the state on this render. - 2The Updater Function (
setState): A function that updates the state variable and triggers React to re-render the component.
ES6 Array Destructuring
Because useState returns a 2-element array [currentValue, updaterFunction], React developers use ES6 array destructuring to assign custom names:
Convention: If the state variable is named foo, the updater function is conventionally named setFoo.
3. A Complete Working Example: Interactive Counter
4. How useState Works Across Renders
Let's trace what happens when the user clicks "Increment (+)":
- 1Initial Mount:
- React executes
Counter(). useState(0)returns[0, setCount].- React renders
<p>Current value: 0</p>.
- 1User Clicks Increment:
setCount(0 + 1)is called with value1.- React records the new state for this component instance as
1and queues a re-render.
- 1Re-render:
- React executes
Counter()a second time. useState(0)is invoked again, but React remembers that state is now1! It returns[1, setCount].- React renders
<p>Current value: 1</p>. - React diffs the Virtual DOM and updates the text node in the real DOM from
0to1.
5. Lazy Initial State
If your initial state requires an expensive computation (e.g., parsing a large JSON file or reading from localStorage), do not execute the function directly in useState(...) because it will run on every single render:
Practice Quiz
useState hook return?useState(initialValue)?useState(() => getInitialData())?setCount(5) when the current count is already 5?Updating State and Immutable Updates
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Introduction to Component State | Updating State and Immutable Updates |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.