Repository navigation
useState
vinibiavatti1 edited this page Sep 28, 2026
·
2 revisions
Declares a reactive state variable. When updated, React re-renders the component. State must be treated as immutable. Always return a new object or array reference (e.g., using the spread operator) so React can detect changes.
import { useState } from 'react';
export const MyComponent = () => {
// Initialization
const [count, setCount] = useState(0);
// Lazy initialization (synchronous)
const [count, setCount] = useState(() => calculateCount());
// Direct update
setCount(5);
// Update based on previous state
setCount(prev => prev + 1);
// Object example
const [user, setUser] = useState({ id: 1, name: 'John' });
setUser(prev => ({ ...prev, name: 'Jane' }));
// Array example
const [items, setItems] = useState(['Computer', 'Keyboard']);
setItems(prev => [...prev, 'Screen']);
}- Home
- Functional Components
- Props
- Fragments
- Memoization
- Forward Ref
- Portals
- Suspense
-
Hooks
- State
- Context
- Effect
- Ref
- Performance
- Concurrent
- Form
- Utility
- Custom Hooks