Beginner LevelReact JS & React 19
How does useEffect work and how do dependency arrays control execution?
❓ Interview Prompt: Explain useEffect lifecycle mapping, dependency arrays (empty vs populated vs omitted), and cleanup functions.
'useEffect' lets you synchronize a component with an external system (network, DOM, timers, subscriptions).
Dependency Array Rules:
1
No Dependency Array ('useEffect(fn)'): Runs after every render. Highly prone to infinite loops if state is updated inside.
2
Empty Array ('useEffect(fn, [])'): Runs once after initial mount (like 'componentDidMount'). Cleanup runs on unmount.
3
Populated Array ('useEffect(fn, [id])'): Runs on mount AND after any render where 'id' has changed (compared via 'Object.is').
Cleanup Function:
Return a function from 'useEffect' to clean up subscriptions, timers, or event listeners before the component unmounts or before the effect re-runs.
Code Implementation Example
jsx
function UserStatus({ userId }) {
const [status, setStatus] = useState('offline');
useEffect(() => {
// 1. Setup: Subscribe to user status
const subscription = ChatAPI.subscribe(userId, setStatus);
// 2. Cleanup: Unsubscribe on unmount OR when userId changes
return () => {
subscription.unsubscribe();
};
}, [userId]); // Re-subscribes only when userId changes
}💡useEffect lifecycle subscription setup and cleanup return function.
🎯 Interview Key Takeaway
Return a cleanup function from useEffect to unsubscribe from timers, WebSockets, or global event listeners safely.
#useEffect#Lifecycle#Cleanup#Hooks#Beginner
Back to all React JS & React 19 Questions→