Home
React
React Hook: useEffect()
Daniel Nguyen
Daniel Nguyen
July 08, 2025
1 min

useEffect is a React Hook that lets you synchronize a component with external systems, such as APIs, timers, event listeners, or third-party libraries.

1. What Is useEffect?

An effect runs after React commits a render. Its dependency array determines when React re-runs the effect.

useEffect(() => {
// Side effect
}, [dependencies]);

Example: Timer

useEffect(() => {
const id = setInterval(() => {
console.log("tick");
}, 1000);
return () => clearInterval(id);
}, []);

The timer starts when the component mounts and stops when the component unmounts.

2. Effect Cleanup

Some effects create ongoing work, such as timers, event listeners, or subscriptions. Return a cleanup function to stop that work when the effect is re-run or the component unmounts.

useEffect(() => {
const handleResize = () => {
console.log(window.innerWidth);
};
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);

The cleanup function removes the event listener, preventing duplicate subscriptions and unwanted behavior.

3. Dependency Array

The dependency array determines when an effect runs again.

// After every commit
useEffect(() => {
console.log("Rendered");
});
// When the component mounts, and during Strict Mode's
// extra development setup cycle
useEffect(() => {
console.log("Mounted");
}, []);
// When count changes
useEffect(() => {
console.log(count);
}, [count]);

React compares dependencies using Object.is. Include every reactive value used by the effect to avoid stale values.


Tags

#ReactHook

Share

Daniel Nguyen

Daniel Nguyen

Frontend Developer

Frontend developer specializing in React, Next.js, and JavaScript. Writing practical guides on modern web development at Dev98.

Expertise

React
Next.js
JavaScript
TypeScript
Python

Social Media

githublinkedinyoutubewebsite

Related Posts

React Hook
React Hook: useRef()
July 10, 2025
1 min
Dev98

Dev98

React · Next.js · Web development