How to Use useEffect in Next.js: Simple Guide with Examples
In Next.js, you use the
useEffect hook inside functional components to run side effects like fetching data or updating the DOM after rendering. Place your effect code inside useEffect(() => { ... }, [dependencies]) to control when it runs, such as on mount or when values change.Syntax
The useEffect hook takes two arguments: a function that contains your side effect code, and an optional array of dependencies that control when the effect runs.
- Effect function: Runs after the component renders.
- Dependencies array: When values inside this array change, the effect runs again. If empty, it runs only once after the first render.
javascript
useEffect(() => {
// Your side effect code here
return () => {
// Optional cleanup code here
};
}, [dependencies]);Example
This example shows a Next.js functional component that uses useEffect to fetch user data once when the component mounts and displays it.
javascript
import { useState, useEffect } from 'react'; export default function UserProfile() { const [user, setUser] = useState(null); useEffect(() => { async function fetchUser() { const response = await fetch('https://jsonplaceholder.typicode.com/users/1'); const data = await response.json(); setUser(data); } fetchUser(); }, []); // Empty array means run once on mount if (!user) return <p>Loading user data...</p>; return ( <div> <h1>{user.name}</h1> <p>Email: {user.email}</p> </div> ); }
Output
<h1>Leanne Graham</h1><p>Email: Sincere@april.biz</p>
Common Pitfalls
Common mistakes when using useEffect in Next.js include:
- Not providing a dependencies array, causing the effect to run after every render and possibly creating infinite loops.
- Using server-only code inside
useEffectwhich runs only on the client, leading to unexpected behavior. - Forgetting to clean up subscriptions or timers inside the effect, causing memory leaks.
javascript
/* Wrong: Missing dependencies array causes repeated runs */ useEffect(() => { console.log('Runs after every render'); }); /* Right: Empty array runs only once on mount */ useEffect(() => { console.log('Runs once on mount'); }, []);
Quick Reference
Remember these tips when using useEffect in Next.js:
- Use an empty dependency array
[]to run effect once on mount. - Include variables in dependencies to rerun effect when they change.
- Clean up side effects by returning a function inside
useEffect. - Next.js runs
useEffectonly on the client side.
Key Takeaways
Use
useEffect inside Next.js functional components to run side effects after rendering.Provide a dependencies array to control when the effect runs and avoid infinite loops.
Effects run only on the client side in Next.js, so avoid server-only code inside
useEffect.Always clean up subscriptions or timers inside
useEffect to prevent memory leaks.An empty dependencies array runs the effect once after the component mounts.