React
useEffect
Side-effect Hook.
By EZ4Code Team
reacthook
Code
import { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
// Run on mount and when userId changes
useEffect(() => {
let cancelled = false;
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => {
if (!cancelled) setUser(data);
});
// Cleanup function
return () => { cancelled = true; };
}, [userId]);
if (!user) return <div>Loading...</div>;
return <div>{user.name}</div>;
}
// Event listener
function WindowSize() {
const [size, setSize] = useState(window.innerWidth);
useEffect(() => {
const handler = () => setSize(window.innerWidth);
window.addEventListener('resize', handler);
return () => window.removeEventListener('resize', handler);
}, []);
return <div>Width: {size}px</div>;
}
// Timer
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(s => s + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <div>{seconds}s</div>;
}
// Run only on mount
function MountOnly() {
useEffect(() => {
console.log('Mounted');
}, []);
return <div>Hello</div>;
}Explanation
useEffect handles side effects; the dependency array controls execution timing; the cleanup function prevents memory leaks.
More React Snippets
Controlled Form with Validation
Build a controlled React form with inline validation and error messages.
Event Handling and List Rendering
Handle events and render dynamic lists with keys in React.
useState
State management Hook.
useContext
Shared state via context.
useReducer
Complex state management.
useMemo
Memoize computation results.