Topic 26 of 54
The useEffect Hook
Overview
`useEffect` is the hook used to execute side effects. You use it to connect to chat rooms, fetch data from an API, set up timers, or directly manipulate the DOM (like changing the document title). It takes two arguments: a function containing the effect logic, and an optional dependency array that controls *when* the effect runs.
Syntax
The setup function modifies the browser's document title (an external system). We tell React to only run this setup function if the `count` variable actually changed since the last render.
Basic useEffect Syntax
jsx
import { useEffect, useState } from 'react';
function DocumentTitleUpdater() {
const [count, setCount] = useState(0);
// useEffect(setupFunction, dependencyArray)
useEffect(() => {
// This code runs AFTER the component renders
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run this effect if 'count' changes
return <button onClick={() => setCount(c => c + 1)}>Click Me</button>;
}Common Pitfalls
- Putting an asynchronous function directly as the setup function (e.g., `useEffect(async () => {...})`). React expects the setup function to return either nothing or a cleanup function, not a Promise.
Interview Tips
- Be able to clearly define a 'Side Effect': any operation that affects something outside the scope of the function being executed (e.g., Network requests, DOM manipulation, Timers).
Real-World Example
Tracking page views for analytics when a user visits a specific route.
example
jsx
function ProductPage({ productId }) {
useEffect(() => {
// Send an event to Google Analytics
Analytics.trackPageView('product_view', { id: productId });
}, [productId]); // Re-track if the user navigates to a different product
return <ProductDetails id={productId} />;
}