Reacts useEffect hook is one of the most powerful and commonly misunderstood tools. Whether you’re fetching data, adding event listeners, or syncing state, useEffect makes it possible.
useEffect
hook is one of the most powerful and commonly misunderstood tools. Whether you’re fetching data, adding event listeners, or syncing state, useEffect
makes it possible.useEffect
?useEffect
?useEffect
is a React Hook that lets you run side effects in function components. Side effects include:useEffect
?useEffect
in Next.jsuseEffect
works the same way, but you must not use it for SSR logic — it runs only on the client.getServerSideProps
or getStaticProps
for server-side data fetching, and useEffect
for client-side actions.useEffect
useEffect
:AbortController
for fetch cancellation.useEffect
calls.Use case | When to use useEffect ? |
Fetch API data | On component mount or param change |
Set interval or timeout | On mount, and clean up on unmount |
DOM manipulation | For client-side interactions only |
Event listeners | Add on mount, remove on unmount |
Syncing props/state | Carefully with dependency array |
useEffect
is a swiss-army knife — powerful but easy to misuse. Understand when and why you’re using it. When used correctly, it allows you to build dynamic, performant, and reactive applications.import { useEffect } from 'react'; useEffect(() => { // This code runs after the component mounts });
useEffect(() => { // Side-effect logic return () => { // Cleanup (runs when the component unmounts or before next effect) }; }, [dependencies]);
import { useEffect, useState } from 'react'; function UserProfile({ userId }) { const [user, setUser] = useState(null); useEffect(() => { async function fetchUser() { const res = await fetch(`/api/user/${userId}`); const data = await res.json(); setUser(data); } fetchUser(); }, [userId]); // Refetch if userId changes if (!user) return <p>Loading...</p>; return <div>{user.name}</div>; }
import { useState, useEffect } from 'react'; function WindowSize() { const [width, setWidth] = useState(window.innerWidth); useEffect(() => { const handleResize = () => setWidth(window.innerWidth); window.addEventListener('resize', handleResize); return () => { // Clean up window.removeEventListener('resize', handleResize); }; }, []); return <p>Window width: {width}px</p>; }
import { useEffect } from 'react'; function Countdown() { useEffect(() => { const timer = setInterval(() => { console.log('Tick...'); }, 1000); return () => clearInterval(timer); }, []); return <div>Timer running...</div>; }
import { useEffect } from 'react'; export default function Page() { useEffect(() => { console.log("Page view logged"); }, []); return <h1>Welcome to the page</h1>; }
useEffect(() => { fetchData(); // will run on every render if [] is missing });
useEffect(() => { fetchData(); }, []);
useEffect(() => { setCounter(counter + 1); }, [counter]);