useState Hook: State and Re-renders
Call useState to add local state to a component, update state with the setter function, and understand when and why React re-renders.
What Is State?
State is data that changes over time and should cause the UI to update when it does. Unlike regular variables, state changes trigger React to re-render the component with the new value.
useState Syntax
useState(initialValue) returns a tuple: the current value and a setter function. Destructure it immediately.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // initial value: 0
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
<button onClick={() => setCount(count - 1)}>-</button>
</div>
);
}All lessons in this course
- JSX: Syntax and Transpilation
- Functional Components and Props
- useState Hook: State and Re-renders
- Lists Keys and Conditional Rendering