Loading lessons...
Component State with useState
Component State with useState
Props pass data down from parent components, but components often need to track and update their own local data over time (such as button clicks, text inputs, or toggle switches). React handles component memory via State.
What is State?
State is component-specific data that changes over time. When state updates, React automatically triggers a re-render of the component and updates the DOM to reflect the new state.
The useState Hook Syntax
The useState Hook is imported from react. Calling useState(initialValue) returns an array with exactly two elements:
- Current State Value: The variable holding the current state snapshot.
- State Setter Function: The function used to update the state and trigger re-renders.
import { useState } from 'react';
function Counter() {
// Array destructuring to unpack state variable and setter function
const [count, setCount] = useState(0);
return (
<div>
<p>Current Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<button onClick={() => setCount(0)}>
Reset
</button>
</div>
);
}
How State Updates Trigger Re-renders
Calling setCount(newVal) notifies React that state has changed. React schedules a re-render of the component, computes the new Virtual DOM, diffs it against the old VDOM, and updates the real DOM text node.
[ User Click ] -> [ call setter function: setCount(1) ] -> [ React Re-renders Component ] -> [ DOM updated ]
Summary & TL;DR
- State holds local component data that can change over time.
- Import
useStatefrom'react'. - Destructure the returned tuple:
const [state, setState] = useState(initialValue). - Updating state via setter functions triggers component re-renders automatically.