useEffect Hook
Learn how to use the useEffect Hook to synchronize React components with external systems, respond to state changes, and perform operations such as fetching data and managing browser events.
1. What Is the useEffect Hook?
The useEffect Hook is a built-in React Hook that allows functional components to synchronize with external systems. It can be used for operations such as fetching data from an API, subscribing to events, and working with timers.
An Effect runs after React commits a render. Depending on its dependency array, it can run after the initial mount and again when specified dependencies change.
useEffect from React before using it.
Effects are intended for synchronizing with external systems,
not for every calculation performed during rendering.
2. Syntax of useEffect
The basic syntax is:
useEffect(() => {
// Effect logic
return () => {
// Optional cleanup logic
};
}, [dependencies]);
- Effect function: Contains the operation that React should synchronize.
- Cleanup function: Optionally removes subscriptions, clears timers, or reverses setup work.
- Dependency array: Specifies the reactive values that determine when the Effect should run again.
3. How useEffect Works
React renders the component and commits the changes. After that, the Effect runs when required by its dependencies.
4. Basic Example of useEffect
In this example, the Effect runs after the component commits its initial render because the dependency array is empty.
Example Code
import { useEffect } from "react";
function App() {
useEffect(() => {
console.log("Component rendered");
}, []);
return (
<div>
<h2>useEffect Example</h2>
<p>Open the browser console.</p>
</div>
);
}
export default App;
Expected Output
useEffect Example
Open the browser console.
Console message after the initial Effect runs:
Component rendered[] means this Effect
does not re-run because of changes to reactive dependencies.
In development Strict Mode, React may run an additional
setup and cleanup cycle to help detect problems.
5. useEffect with a Dependency
We can provide a state variable in the dependency array. The Effect then runs after the initial commit and again whenever that dependency changes.
Example Code
import { useEffect, useState } from "react";
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<h2>Counter Example</h2>
<p>Count: {count}</p>
<button onClick={() =>
setCount(count + 1)
}>
Increase
</button>
</div>
);
}
export default App;
Expected Output
Initially, the page displays:
Count: 0After clicking Increase:
Count: 1The browser tab title changes to Count: 1.
count state is included in the dependency
array. Whenever count changes, React runs the Effect again
and updates the browser tab title.
6. Understanding the Dependency Array
Without a Dependency Array
useEffect(() => {
console.log("Effect executed");
});
The Effect runs after every committed render. If the Effect updates state on every render without a suitable condition, it can cause repeated rendering.
With an Empty Dependency Array
useEffect(() => {
console.log("Initial Effect");
}, []);
The Effect runs after the initial commit. Development Strict Mode may perform an extra setup and cleanup cycle.
With a Dependency
useEffect(() => {
console.log("Count changed:", count);
}, [count]);
The Effect runs after the initial commit and again when
the value of count changes.
7. Why Is Effect Cleanup Important?
Some Effects create resources that must be released. For example, a timer, event listener, or subscription may continue working even when it is no longer needed. Cleanup helps prevent unnecessary work and resource leaks.
Example Code
import { useEffect } from "react";
function App() {
useEffect(() => {
function handleResize() {
console.log(window.innerWidth);
}
window.addEventListener(
"resize",
handleResize
);
return () => {
window.removeEventListener(
"resize",
handleResize
);
};
}, []);
return (
<div>
<h2>Window Resize Example</h2>
<p>Resize the browser window and check
the console.</p>
</div>
);
}
export default App;
Expected Output
Window Resize Example
Resize the browser window and check the console to see the current window width.
8. Important Points About useEffect
-
Import
useEffectfrom React. - Call Hooks at the top level of a component or custom Hook.
- Use the dependency array to control when an Effect needs to synchronize again.
- Return a cleanup function when setup creates something that must be released.
- Avoid updating state unnecessarily inside an Effect, as it may trigger additional renders.
- Use Effects for synchronization with external systems, such as event listeners, subscriptions, and network APIs.
9. Practice Tasks
Complete these exercises to practise the useEffect Hook:
- Create a component that logs a message after its initial render.
- Create a counter that updates the browser tab title whenever the count changes.
- Create an Effect that logs a message when a selected course changes.
- Register a window resize event listener and remove it using a cleanup function.
- Compare an Effect with an empty dependency array and an Effect without a dependency array.