useEffect Deep DiveBeginner
1Question 1 of 1
javascriptWhat are the common pitfalls and best practices of useEffect dependencies?
Explanation & Concept
Common `useEffect` pitfalls include: 1. Omitting dependencies from the dependency array, causing stale closure bugs. 2. Passing non-primitive objects or inline functions as dependencies, causing infinite re-render loops. 3. Forgetting cleanup functions, leading to unhandled memory leaks.
Best practice: Use the `eslint-plugin-react-hooks` linter to enforce exhaustive dependencies.
Code Example
javascript
import { useState, useEffect } from "react";
export function UserStatus({ userId }) {
const [status, setStatus] = useState("offline");
useEffect(() => {
let isSubscribed = true;
async function checkStatus() {
const response = await fetch(`/api/status/${userId}`);
const data = await response.json();
// Guard against updating state if component unmounted or userId changed
if (isSubscribed) {
setStatus(data.status);
}
}
checkStatus();
return () => {
isSubscribed = false; // Cleanup flag
};
}, [userId]); // Re-runs cleanly whenever userId changes
return <span>User status: {status}</span>;
}How It Works & Key Takeaways
Using an `isSubscribed` boolean guard avoids the common React error: 'Can't perform a React state update on an unmounted component'.
Mock Test · 1 Questions · Optional
Ready for Custom Hooks?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions