Understanding Side Effects in React JS – Complete Detailed Notes
Course: React JS Training
Topic: Understanding Side Effects
Level: Beginner to Advanced
1. Introduction to Side Effects
In React JS, a side effect is an operation that interacts with something outside the component's pure rendering calculation. Side effects can include fetching data from an API, updating the browser document title, creating timers, registering event listeners, connecting to a server, or interacting with a third-party library.
React components should ideally calculate their user interface from their current props and state. Operations that interact with external systems should be handled in appropriate places, such as event handlers or Effects, rather than being performed directly during rendering.
React's useEffect Hook is commonly used when a component needs to synchronize with an external system as a result of rendering.
Definition
A side effect is an operation that does more than calculate the output of a component. It may communicate with external systems, change an external resource, or perform an action outside React's rendering process.
Examples of Side Effects
- Fetching information from a REST API.
- Updating the browser tab title.
- Starting or stopping a timer.
- Adding or removing browser event listeners.
- Connecting to a WebSocket or chat server.
- Synchronizing with local storage.
- Controlling a video player or third-party widget.
- Sending analytics information when appropriate.
Official reference: React – Synchronizing with Effects
2. Understanding Pure Rendering
Rendering is the process in which React calls a component to determine what should appear on the screen. A component should calculate its JSX from props, state, and other values without modifying external systems during the calculation.
Example of Pure Rendering
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
export default Greeting;
This component receives a name and returns JSX. It does not modify an external resource, start a timer, or send a network request.
Example of an Incorrect Side Effect During Rendering
function Counter() {
document.title = "Counter Page";
return <h1>Counter</h1>;
}
export default Counter;
In this example, the component changes the browser document title directly during rendering. Rendering may happen more than once, so performing external operations here can lead to unexpected behavior.
Better Approach
import { useEffect } from "react";
function Counter() {
useEffect(() => {
document.title = "Counter Page";
}, []);
return <h1>Counter</h1>;
}
export default Counter;
Now the document title is synchronized through an Effect after React commits the component.
3. Why Are Side Effects Important?
Most real-world React applications need to communicate with systems outside React. These interactions allow an application to display live information, respond to browser events, save data, and work with external services.
Importance of Side Effects
- Data fetching: Retrieves information from APIs and servers.
- Browser interaction: Updates the document title or listens for browser events.
- Resource management: Starts and stops timers, subscriptions, and connections.
- Data persistence: Synchronizes information with local storage or other storage systems.
- Third-party integration: Connects React components with maps, charts, video players, or other libraries.
- Application synchronization: Keeps React state and an external system consistent.
Real-World Example
Consider a weather application. React renders the weather information, but the weather data may come from an external API. The application must request the information, handle loading and error states, and then display the result. The network request is a side effect; rendering the resulting weather information is the component's rendering responsibility.
4. Understanding the useEffect Hook
The useEffect Hook allows a React component to synchronize with an external system. It accepts a setup function and an optional dependency array. The setup function may return a cleanup function when resources need to be released or an operation needs to be undone.
Syntax
import { useEffect } from "react";
useEffect(() => {
// Side-effect or synchronization logic
return () => {
// Optional cleanup logic
};
}, [dependencies]);
Parameters
| Parameter |
Description |
| Setup function |
Contains the logic for synchronizing with an external system. |
| Cleanup function |
Optional function that stops, reverses, or cleans up the synchronization. |
| Dependency array |
Specifies the reactive values that determine when the Effect must run again. |
Important Points
- Call
useEffect at the top level of a function component or custom Hook.
- Effects run after React commits the relevant render.
- Effects without a dependency array run after every commit.
- Effects with an empty dependency array run on the initial mount, with an additional development-only setup and cleanup cycle in Strict Mode.
- Effects with dependencies re-run when their dependency values change.
- Effects do not run during server rendering.
Official reference: React useEffect Documentation
5. Different Types of useEffect Dependency Arrays
The dependency array determines when React needs to repeat an Effect's synchronization work.
5.1 useEffect Without a Dependency Array
useEffect(() => {
console.log("Effect ran after a commit");
});
Behavior: The Effect runs after every commit of the component. Use this form only when repeating the synchronization after every commit is intentional.
5.2 useEffect with an Empty Dependency Array
useEffect(() => {
console.log("Component mounted");
}, []);
Behavior: The Effect runs on the initial mount. In development with Strict Mode enabled, React performs an extra setup and cleanup cycle to help identify missing cleanup logic.
5.3 useEffect with Dependencies
useEffect(() => {
console.log("User ID changed:", userId);
}, [userId]);
Behavior: The Effect runs on the initial mount and runs again when userId changes.
Dependency Array Comparison
| Syntax |
Execution Behavior |
Common Example |
useEffect(fn) |
After every commit |
Intentional repeated synchronization |
useEffect(fn, []) |
Initial mount, plus development Strict Mode checks |
Set up a subscription that lasts while mounted |
useEffect(fn, [value]) |
Initial mount and when value changes |
Synchronize with a selected user or room |
React compares dependency values using Object.is. Include all reactive values used by the Effect. Do not remove dependencies merely to prevent an Effect from running; instead, restructure the code if the dependencies cause unnecessary synchronization.
6. Example: Updating the Browser Document Title
One simple example of a side effect is synchronizing the browser tab title with a value in React state.
Code Example
import { useEffect, useState } from "react";
function TitleUpdater() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(c => c + 1)}>
Increase Count
</button>
</div>
);
}
export default TitleUpdater;
Explanation
- The component initializes the counter with
useState.
- The button updates the counter when clicked.
- React renders the component using the new count.
- The Effect runs because the count dependency has changed.
- The browser tab title is updated to match the current count.
This example demonstrates synchronization between React state and a browser API.
7. Example: Fetching Data from an API
Data fetching is a common requirement in React applications. An Effect can be used to fetch data when a component appears or when a value such as a user ID changes. For larger applications, framework data-loading features or dedicated data-fetching libraries may offer better caching and request management.
Example Using fetch and AbortController
import { useEffect, useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
async function fetchUsers() {
try {
setLoading(true);
setError("");
const response = await fetch(
"https://jsonplaceholder.typicode.com/users",
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Failed to fetch users");
}
const data = await response.json();
setUsers(data);
} catch (err) {
if (err.name !== "AbortError") {
setError(err.message || "Something went wrong");
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
fetchUsers();
return () => {
controller.abort();
};
}, []);
if (loading) {
return <p>Loading users...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
return (
<div>
<h2>Users List</h2>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
export default Users;
Explanation
useState manages the users, loading status, and error message.
useEffect starts the network request.
fetch() sends a request to the API.
response.ok checks whether the HTTP response indicates success.
response.json() parses the response body.
AbortController allows the request to be cancelled during cleanup.
- The interface displays loading, error, or user data according to the current state.
For requests that depend on changing values, such as userId, include that value in the dependency array and ensure stale requests cannot overwrite newer results.
8. Example: Using Side Effects with Timers
A timer is an external browser resource. When an Effect starts a timer, it should normally clear that timer when the Effect is cleaned up.
Example: Digital Counter
import { useEffect, useState } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const timerId = setInterval(() => {
setSeconds(previous => previous + 1);
}, 1000);
return () => {
clearInterval(timerId);
};
}, []);
return (
<div>
<h2>Timer: {seconds} seconds</h2>
</div>
);
}
export default Timer;
Explanation
- The timer starts when the component mounts.
- Every second, the interval updates the state.
- React re-renders the component with the updated number.
- The cleanup function clears the interval when the component unmounts.
The functional state updater previous => previous + 1 uses the latest state value without making the Effect depend on seconds.
9. Understanding Cleanup Functions
A cleanup function reverses or stops work started by an Effect. It is important when an Effect creates a resource that should not remain active after synchronization is no longer needed.
Common Cleanup Operations
| Resource or Operation |
Typical Cleanup |
| Interval timer |
clearInterval() |
| Timeout |
clearTimeout() |
| Browser event listener |
removeEventListener() |
| WebSocket connection |
Close the connection or unsubscribe as appropriate. |
| Subscription |
Unsubscribe from the source. |
| Fetch request |
Abort the request or ignore obsolete results. |
| Third-party animation |
Stop or reset the animation as required. |
Example: Event Listener Cleanup
import { useEffect, useState } from "react";
function WindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function updateWidth() {
setWidth(window.innerWidth);
}
window.addEventListener("resize", updateWidth);
return () => {
window.removeEventListener("resize", updateWidth);
};
}, []);
return <p>Window width: {width}px</p>;
}
export default WindowWidth;
This example is for a browser-rendered application. If the component is rendered on a server, initialize browser-dependent state in a way that safely handles the absence of window.
When Does Cleanup Run?
- Before the Effect runs again with changed dependencies.
- When the component unmounts.
- During the additional development-only Strict Mode setup and cleanup check.
10. Side Effects vs Event Handlers
Not every side effect belongs inside useEffect. The correct location depends on what causes the operation to happen.
An Effect is appropriate when synchronization is caused by the component being rendered with particular props or state. An event handler is appropriate when an action is caused by a specific user interaction, such as clicking a button.
| Requirement |
Suitable Location |
Reason |
| Connect to a chat room while it is displayed |
useEffect |
The connection follows the component's presence and room settings. |
| Buy a product after a button click |
Click event handler |
The purchase is caused by a specific user action. |
| Update the document title based on state |
useEffect |
The external title must stay synchronized with the state. |
| Submit a form after the user presses Submit |
Form submission handler |
The operation is caused by the user's submission. |
| Start a timer while a component is active |
useEffect |
The timer must be set up and cleaned up with the component's lifecycle. |
Incorrect Example: Purchasing in an Effect
useEffect(() => {
fetch("/api/buy", { method: "POST" });
}, []);
This is unsuitable for a purchase because mounting or remounting the component could trigger the request again. A purchase should normally be initiated by the relevant event handler, with appropriate server-side safeguards.
Better Example
async function handleBuy() {
const response = await fetch("/api/buy", {
method: "POST"
});
if (!response.ok) {
throw new Error("Purchase failed");
}
}
Connect this function to a button's click handler and implement appropriate loading and error handling for the application.
11. Side Effects and the React Component Lifecycle
React components are commonly described in terms of three lifecycle stages: mounting, updating, and unmounting. Effects provide a way to manage synchronization across these stages.
Mounting
Mounting occurs when a component is added to the screen. React commits the component and then runs its Effect setup when appropriate.
Updating
Updating occurs when props or state change. If an Effect's dependencies change, React first runs the previous cleanup function, then runs the new setup function.
Unmounting
Unmounting occurs when the component is removed from the screen. React runs the cleanup function for any active Effect that provides one.
Lifecycle Example
useEffect(() => {
console.log("Effect setup");
return () => {
console.log("Effect cleanup");
};
}, [value]);
When value changes, React cleans up the previous synchronization before starting the next one. When the component unmounts, React performs the final cleanup.
12. Understanding Strict Mode and Double Execution in Development
When React Strict Mode is enabled, React performs an additional development-only setup and cleanup cycle for Effects to help identify missing cleanup logic. This behavior is intended to expose bugs and does not mean that Effects should be made to run only once through a workaround.
Example
useEffect(() => {
console.log("Setup");
return () => {
console.log("Cleanup");
};
}, []);
In development with Strict Mode, the initial sequence can be:
- Setup runs.
- Cleanup runs.
- Setup runs again.
This helps verify that cleanup correctly reverses the setup. In production, this extra development check does not occur.
Best Practice
Do not use flags or refs simply to suppress the extra Effect execution. Instead, make the setup and cleanup work correctly together so that the component behaves properly when mounted, updated, or unmounted.
13. Common Side Effect Mistakes
| Mistake |
Problem |
Solution |
| Performing side effects during rendering |
Rendering may run repeatedly, and DOM nodes may not exist yet. |
Use an appropriate Effect or event handler. |
| Missing dependencies |
The Effect can use outdated props or state. |
Include all required reactive dependencies. |
| Forgetting cleanup |
Timers, listeners, or connections can remain active. |
Return a cleanup function when needed. |
| Updating state inside an Effect unnecessarily |
Can cause extra renders or an infinite loop. |
Calculate derived values during rendering when possible. |
| Making an Effect callback async directly |
An async function returns a Promise instead of a cleanup function. |
Define an async function inside the Effect and call it. |
| Using an Effect for a click-driven action |
The action may run on mounting or remounting rather than the click. |
Place the operation in the event handler. |
| Ignoring obsolete network responses |
An older response may overwrite newer data. |
Abort requests or ignore results that are no longer relevant. |
| Using useLayoutEffect for every side effect |
It can block browser painting. |
Prefer useEffect unless pre-paint layout work is required. |
14. Avoiding Infinite Loops in useEffect
An infinite loop can occur when an Effect updates state and that update causes the Effect to run again without a condition or stable dependency arrangement.
Incorrect Example
import { useEffect, useState } from "react";
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
setCount(count + 1);
});
return <p>Count: {count}</p>;
}
The Effect runs after every commit. Updating the count triggers another render, which causes the Effect to run again.
Better Approach
If the goal is simply to initialize the counter to a value, provide that value to useState rather than using an Effect. If a state update truly depends on an external synchronization, identify the appropriate dependencies and avoid unnecessary updates.
const [count, setCount] = useState(1);
15. Side Effects vs Derived State
Derived state is a value that can be calculated from existing props or state. You usually do not need an Effect to calculate it.
Incorrect Approach
const [firstName, setFirstName] = useState("Manish");
const [lastName, setLastName] = useState("Negi");
const [fullName, setFullName] = useState("");
useEffect(() => {
setFullName(`${firstName} ${lastName}`);
}, [firstName, lastName]);
Better Approach
const [firstName, setFirstName] = useState("Manish");
const [lastName, setLastName] = useState("Negi");
const fullName = `${firstName} ${lastName}`;
In the second example, fullName is calculated during rendering. There is no need for an Effect or a separate state variable because the value is completely determined by the other two state values.
16. Best Practices for Managing Side Effects
- Keep rendering pure: do not modify external systems while calculating JSX.
- Use Effects for synchronization: connect React state or component presence with external systems.
- Use event handlers for user actions: place click-driven purchases, submissions, and similar operations in the appropriate handlers.
- Declare dependencies correctly: include the reactive values used by an Effect.
- Clean up resources: release listeners, timers, subscriptions, and connections when no longer needed.
- Handle asynchronous work carefully: consider loading states, errors, cancellation, and stale responses.
- Avoid unnecessary Effects: derive values during rendering when possible.
- Keep Effects focused: separate unrelated synchronization processes when that makes the code clearer.
- Test in Strict Mode: use development checks to identify missing cleanup and other bugs.
- Consider data-fetching tools: for larger applications, framework data-loading mechanisms or libraries can provide caching, request deduplication, and improved data management.
17. Side Effects in Real-World React Applications
| Application |
Side Effect |
Typical Approach |
| E-commerce |
Load product data |
Data-fetching mechanism or Effect when appropriate |
| Chat application |
Connect to a chat server |
Effect with connection cleanup |
| Weather application |
Retrieve weather data |
Data fetching with loading and error handling |
| Task manager |
Synchronize tasks with local storage |
Effect when synchronization is required |
| Video player |
Play or pause an external media element |
Effect to synchronize the player with props |
| Analytics dashboard |
Subscribe to live updates |
Effect with unsubscribe or disconnect cleanup |
| Responsive interface |
Listen for browser resize events |
Effect with event listener cleanup |
| Payment form |
Submit a payment |
Form submission handler and server-side validation |
18. Interview Questions and Answers
Q1. What is a side effect in React?
Answer: A side effect is an operation that interacts with an external system or changes something outside the pure rendering calculation, such as fetching data, setting a timer, or updating the document title.
Q2. Which Hook is commonly used to manage side effects?
Answer: useEffect is commonly used to synchronize a component with external systems.
Q3. What is the purpose of the dependency array?
Answer: It tells React which reactive values determine when an Effect needs to run again.
Q4. What happens when useEffect has no dependency array?
Answer: Its setup function runs after every commit of the component.
Q5. What does an empty dependency array mean?
Answer: The Effect runs on the initial mount. With Strict Mode enabled, development includes an extra setup and cleanup cycle.
Q6. What is a cleanup function?
Answer: It is a function returned by an Effect to stop or undo synchronization, such as clearing a timer or removing an event listener.
Q7. Why should side effects not be performed during rendering?
Answer: Rendering should remain a pure calculation. React can render more than once, and external operations during rendering can cause inconsistent behavior.
Q8. What causes an infinite loop in useEffect?
Answer: A common cause is an Effect updating state on every run, causing another render and another Effect run without an appropriate stopping condition.
Q9. Can useEffect be used to fetch data?
Answer: Yes. It can fetch data when synchronization is appropriate, but the implementation should handle errors, cancellation or obsolete responses, and loading states.
Q10. Why does useEffect sometimes run twice in development?
Answer: React Strict Mode performs an additional setup and cleanup cycle to help developers find Effects that do not clean up correctly.
Q11. Should every API request be placed in useEffect?
Answer: No. Requests caused by a specific user action, such as submitting a form or purchasing an item, usually belong in the relevant event handler. Data synchronization can be handled through Effects or suitable data-fetching tools.
Q12. What is the difference between useEffect and useLayoutEffect?
Answer: useEffect is appropriate for most external synchronization. useLayoutEffect is used when layout measurement or visual correction must happen before the browser repaints.
Q13. What happens if cleanup is missing?
Answer: A timer, listener, or connection may remain active after it is no longer needed, potentially causing duplicated work, memory leaks, or incorrect behavior.
Q14. Do Effects run during server rendering?
Answer: No. Effects run on the client, not during server rendering.
Q15. How can unnecessary Effects be avoided?
Answer: Calculate derived values during rendering, use event handlers for user-triggered actions, and reserve Effects for synchronization with external systems.
19. Practice Exercises
- Create a component that updates the browser tab title when a counter changes.
- Fetch a list of users from an API and display loading and error messages.
- Create a timer using
setInterval() and clear it with a cleanup function.
- Listen for the browser's resize event and display the current window width.
- Create a component that connects to a simulated external service and disconnects during cleanup.
- Build a search component that fetches results when the search term changes and handles outdated requests.
- Identify an Effect that calculates derived state and replace it with a direct calculation.
- Test an Effect in Strict Mode and verify that setup and cleanup work correctly.
20. Quick Revision Checklist
- Understand the meaning of side effects.
- Keep React rendering pure.
- Use
useEffect to synchronize with external systems.
- Understand the three dependency array patterns.
- Include the correct reactive dependencies.
- Use cleanup functions for timers, subscriptions, listeners, and connections.
- Handle API loading states, errors, and outdated requests.
- Use event handlers for actions caused by specific user interactions.
- Avoid Effects for values that can be calculated during rendering.
- Understand why Strict Mode performs extra development checks.
- Use
useLayoutEffect only when pre-paint layout work is needed.
21. Official React Learning Resources
22. React JS Training and Course Demo
Learn React fundamentals, Hooks, component lifecycle concepts, API integration, event handling, and practical application development through these course resources.
JustAcademy React JS Training
Register for React JS Course Demo
23. Conclusion
Understanding side effects is essential for developing reliable React applications. Side effects allow components to communicate with external systems, retrieve data, manage timers, listen for browser events, and synchronize with third-party tools.
The useEffect Hook is a key tool for this work, but it should not be used for every operation. Keep rendering pure, use event handlers for user-triggered actions, declare Effect dependencies correctly, and clean up resources when synchronization ends.
Final takeaway: Use Effects when React needs to synchronize with something outside React, and keep ordinary calculations and user-triggered actions in their appropriate places.