Comprehensive examples of React hooks with interactive demos, from basic state management to advanced patterns
Essential React hooks for state management, side effects, and performance optimization
Essential React hooks for managing state, side effects, and performance optimization
The most basic hook for managing component state
Simple state management with useState
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);Managing text input with controlled components
Hello, Anonymous!
const [name, setName] = useState("");
return (
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name..."
/>
);Hook for side effects like timers, API calls, and subscriptions
Creating a timer that updates every second
const [timer, setTimer] = useState(0);
const [isRunning, setIsRunning] = useState(false);
useEffect(() => {
let interval;
if (isRunning) {
interval = setInterval(() => {
setTimer(timer => timer + 1);
}, 1000);
}
return () => clearInterval(interval);
}, [isRunning]);Optimize performance by memoizing callback functions
Preventing unnecessary re-renders with memoized callbacks
const addTodo = useCallback((todo) => {
setTodos(prev => [...prev, todo]);
}, []);
const removeTodo = useCallback((index) => {
setTodos(prev => prev.filter((_, i) => i !== index));
}, []);Optimize performance by memoizing expensive calculations
Memoizing expensive computations to prevent unnecessary recalculations
Calculated Result: 30
Check console for memoization logs
const expensiveCalculation = useMemo(() => {
console.log("Computing expensive calculation...");
return numbers.reduce((sum, num) => sum + (num * multiplier), 0);
}, [numbers, multiplier]);Access DOM elements and persist values across renders
Using useRef to directly manipulate DOM elements
Focus count: 0
The focus count persists across renders without causing re-renders
const inputRef = useRef(null);
const [focusCount, setFocusCount] = useState(0);
const focusInput = () => {
inputRef.current?.focus();
setFocusCount(prev => prev + 1);
};
return (
<input ref={inputRef} />
);Advanced hooks with complex interactions, real-time updates, and context management
Advanced hooks with complex interactions, real-time updates, and context management
Manage complex state logic with reducer pattern
Complex state management with actions and history tracking
History (0 actions):
const [state, dispatch] = useReducer(counterReducer, {
count: 0,
step: 1,
history: []
});
function counterReducer(state, action) {
switch (action.type) {
case 'increment':
return {
...state,
count: state.count + state.step,
history: [...state.history, state.count]
};
// ... other cases
}
}Share data across components without prop drilling
Global theme management using Context API
This theme state is managed by useContext and shared across the entire component tree without prop drilling!
const ThemeContext = createContext();
function useTheme() {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within ThemeProvider');
}
return context;
}
function ThemeConsumer() {
const { theme, setTheme } = useTheme();
return <div>Current theme: {theme}</div>;
}Complex side effects with real-time updates and cleanup
Real-time progress tracking with multiple downloads
useEffect(() => {
const interval = setInterval(() => {
setDownloads(prev => prev.map(download => {
if (download.status === 'downloading' && download.progress < 100) {
const newProgress = Math.min(download.progress + Math.random() * 10, 100);
return {
...download,
progress: newProgress,
status: newProgress === 100 ? 'completed' : 'downloading'
};
}
return download;
}));
}, 500);
return () => clearInterval(interval);
}, []);Synchronous DOM measurements and updates
Real-time mouse tracking and user activity monitoring
Mouse: (0, 0)
Move your mouse and click to see activities!
useLayoutEffect(() => {
const handleMouseMove = (e) => {
setMousePosition({ x: e.clientX, y: e.clientY });
};
const handleClick = () => {
setActivities(prev => [
{ action: `Clicked at (${mousePosition.x}, ${mousePosition.y})`, timestamp: Date.now() },
...prev.slice(0, 9)
]);
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('click', handleClick);
return () => {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('click', handleClick);
};
}, [mousePosition]);Custom hooks, performance optimization, and enterprise-grade patterns for complex applications
Custom hooks, performance optimization, and enterprise-grade patterns for complex applications
Reusable stateful logic with custom hook patterns
Debounce user input to prevent excessive API calls
Immediate:
Empty
Debounced (500ms):
Empty
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => clearTimeout(handler);
}, [value, delay]);
return debouncedValue;
}Persistent state management with localStorage
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = (value) => {
try {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error('Error setting localStorage:', error);
}
};
return [storedValue, setValue];
}Expose imperative APIs to parent components
Access child component methods through refs
const CustomInput = forwardRef((props, ref) => {
const [value, setValue] = useState('');
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
getValue: () => value,
setValue: (newValue) => setValue(newValue)
}));
return <input ref={inputRef} value={value} onChange={e => setValue(e.target.value)} />;
});Real-world patterns for complex applications
Custom hooks for performance tracking and analytics
Component Renders
1,234
Memory Usage
45.2MB
Load Time
1.2s
function usePerformanceMonitor() {
const [metrics, setMetrics] = useState({});
useEffect(() => {
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
setMetrics(prev => ({
...prev,
...processEntries(entries)
}));
});
observer.observe({ entryTypes: ['navigation', 'paint', 'largest-contentful-paint'] });
return () => observer.disconnect();
}, []);
return metrics;
}