State Management with useState
The `useState` hook allows you to create and update local state in functional components.
Key concepts
useState
A hook that allows you to create and update local state in functional components. Returns a state variable and a state updater function.
Step by step
How It Works:
- The state variable (`count`) stores the current value.
- The state updater function (`setCount`) modifies the state.
- React re-renders the component whenever `setState` is called.
When to Use:
- For managing simple, component-specific state like form inputs, toggles, or counters.
Examples
useState Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus