useStateThe useState hook is the fundamental tool for introducing local state into a React functional component. It is imported directly from the 'react' package.
useStateWhen you call useState, you pass the initial state value as an argument. It returns an array containing exactly two items:
state): The current value of the state on this render.setState): A function that updates the state variable and triggers React to re-render the component.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.
useState Works Across RendersLet's trace what happens when the user clicks "Increment (+)":
Counter().useState(0) returns [0, setCount].<p>Current value: 0</p>.setCount(0 + 1) is called with value 1.1 and queues a re-render.Counter() a second time.useState(0) is invoked again, but React remembers that state is now 1! It returns [1, setCount].<p>Current value: 1</p>.0 to 1.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:
useState hook return?useState(initialValue)?useState(() => getInitialData())?setCount(5) when the current count is already 5?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Introduction to Component State | Updating State and Immutable Updates |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.