useEffect:
- In React, the useEffect hook is a built-in function that lets you synchronize a component with external systems and handle side effects in functional components.
- Side effects are operations that happen outside the scope of React's standard rendering process.
- Examples include fetching data from an API, setting up event listeners, creating timers, and manually updating the browser DOM.
syntax:
The useEffect hook accepts two arguments:
- a callback function (the effect itself).
- an optional dependency array.
import { useEffect } from 'react';
useEffect(() => {
// 1. Your side-effect logic goes here
return () => {
// 2. Optional cleanup function goes here
};
}, [dependencies]); // 3. Optional dependency array
How it Works?
The way your effect executes depends entirely on what you pass into the dependency array:
1. No Dependency Array (Runs on every render):
- If you omit the array completely, the effect will run after the initial render and every single update/re-render of the component.
useEffect(() => {
console.log("I run on every single render!");
});
- If you pass an empty array, the effect will only run once, right after the component first appears on the screen (mounts).
- This mimics componentDidMount.
useEffect(() => {
console.log("I run only once when the component mounts.");
}, []);
3. Array with Dependencies value1, value2:
- If you place variables (props or state) inside the array, React will track them.
- The effect will run during the initial render and will re-run only if one of those variables changes between renders.
- This mimics componentDidUpdate.
useEffect(() => {
console.log(`The count changed! It is now: ${count}`);
}, [count]); // Triggers only when 'count' changes
The Cleanup Function:
- Sometimes side effects create persistent behaviors that need to be cleaned up to avoid memory leaks, such as open WebSockets, event listeners, or setInterval timers.
- To handle this, you can return a cleanup function from inside your effect.
- React will execute this cleanup function before the component unmounts (mimicking componentWillUnmount) and right before running the effect again on a dependency change.
Mounting and unmounting:
- In React, mounting is when a component is first created and inserted into the browser's DOM (added to the screen), while unmounting is when that component is removed from the DOM (disappears from the screen)This returned function is known as the cleanup function.
Common Use Cases:
You should use useEffect when your component needs to sync with an external system:
Fetching data: Pulling information from an external API or database on load.
Subscriptions: Establishing WebSockets, Firebase listeners, or chat server connections.
Timers: Initializing native browser mechanisms like setInterval or setTimeout.
Direct DOM updates: Changing document titles or interacting with third-party, non-React UI widgets.

Top comments (0)