What is useState
?
useState
is a React Hook that allows functional components to have state.
const [state, setState] = useState(initialState);
-
state
→ current state value -
setState
→ function to update state -
initialState
→ initial value
Example: Simple Counter
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h1>Counter: {count}</h1>
<button onClick={decrement} style={{ marginRight: '10px' }}>-</button>
<button onClick={increment}>+</button>
</div>
);
};
export default Counter;
Explanation
-
count
starts at0
. - Clicking
+
increases the counter. - Clicking
-
decreases the counter. -
setCount
updates state and triggers a re-render.
Tips
- Each
useState
is independent. - Always use the setter function to update state.
- Functional updates:
setCount(prevCount => prevCount + 1);
- Functional initialization of state:
const [count, setCount] = useState(() => 0);
homework - learn where to use functional initializtion and update.
Top comments (0)