React 18 introduced StrictMode as a powerful tool for identifying potential bugs before they reach production. While often dismissed as noise, these warnings are critical indicators of anti-patterns that can cause unpredictable behavior during development and testing. Specifically, side effects inside useEffect hooks are a frequent culprit. When React renders components in development mode, it intentionally mounts components twice to verify resilience. If your useEffect hook runs side effects (like API calls or DOM manipulations) on every render or both mounts, you will see console warnings. This guide provides a concrete lab scenario to help IT students and junior engineers identify, debug, and fix these issues using modern best practices.
Understanding the StrictMode Warning Mechanism
To effectively debug these warnings, one must first understand why React behaves this way. In development environments, StrictMode wraps components and causes them to mount twice. This double-mounting allows developers to verify that their components do not hold stale state or perform unnecessary actions on cleanup.
When a useEffect hook has dependencies that change slightly between renders, or if it lacks a dependency array entirely, React treats the effect as unstable. In StrictMode, this instability manifests as duplicate execution. The warning typically looks like this:
Warning: An update to ComponentX inside a test was not wrapped in act(...).
Or more specifically for double execution:
Warning: Unexpected side effect detected. The useEffect will be called again when the component is re-rendered.
These messages indicate that your effect is running when it shouldn’t, often leading to infinite loops or duplicate data fetching. The goal is to ensure effects only run when their dependencies actually change and that cleanup functions are executed correctly.
Lab Scenario: The Duplicate API Call Bug
Consider a realistic workplace scenario where a junior engineer builds a dashboard component that fetches user data from an internal REST API. The initial implementation looks functional but triggers StrictMode warnings immediately upon opening the application in development.
Prerequisites
- Node.js version 18 or higher installed.
- A React project initialized via
npx create-react-app my-dashboardor using Vite (npm create vite@latest). - Basic familiarity with JavaScript ES6+ syntax and the React hooks API.
The Problematic Code
Imagine a file named UserProfile.jsx containing the following logic:
import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
// BUG: No dependency array provided. Runs on every render.
useEffect(() => {
console.log('Fetching user data...');
fetch(`/api/users/${userId}`)
.then((res) => res.json())
.then((data) => setUser(data));
// Side effect: Modifying global window object or logging excessively
window.scrollTo(0, 0);
});
if (!user) return <div>Loading...</div>;
return (
<div>
<h1>{user.name}</h1>
<p>Email: {user.email}</p>
</div>
);
}
export default UserProfile;
In this code, the useEffect hook lacks a dependency array. Consequently, it runs on every single render of the component. In StrictMode, React renders the component twice, causing the API call and the scroll action to happen twice. This wastes bandwidth, increases load times, and creates race conditions if the network request fails mid-stream.
Step-by-Step Debugging Process
Follow these numbered steps to resolve the issue in your lab environment.
- Enable StrictMode Globally: Ensure
StrictModeis active. In a Create React App setup, this is default behavior. If using Vite or custom setups, wrap your root component in<React.StrictMode>withinmain.jsx. - Identify Dependencies: Analyze the variables used inside the
useEffectcallback. In the example above,userIdis read from props. ThefetchURL depends onuserId. Therefore,userIdmust be in the dependency array. - Implement Cleanup Logic: Add a cleanup function to handle side effects like event listeners or timers. While
fetchdoesn’t strictly require cleanup for memory leaks, it is best practice to cancel pending requests if the component unmounts before the response arrives. - Refactor the Hook: Update the hook definition to include dependencies and ensure side effects are isolated.
The Corrected Implementation
Replace the buggy code with the following version:
import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
// FIX: Added dependency array [userId].
// Effect runs only when userId changes or initial mount.
useEffect(() => {
console.log(`Fetching data for user ID: ${userId}`);
// Simulated fetch logic
const fetchData = async () => {
try {
const res = await fetch(`/api/users/${userId}`);
if (!res.ok) throw new Error('Network response was not ok');
const data = await res.json();
setUser(data);
} catch (error) {
console.error("Failed to fetch user:", error);
}
};
fetchData();
// Cleanup: Ensure no lingering listeners or timers if added in future
return () => {
console.log('Cleanup: Unmounting UserProfile component');
};
}, [userId]); // Dependency array includes userId
if (!user) return <div>Loading...</div>;
return (
<div>
<h1>{user.name}</h1>
<p>Email: {user.email}</p>
</div>
);
}
export default UserProfile;
Verification Steps and Expected Results
After applying the fix, restart your development server (npm start or npm run dev). Observe the browser console.
Expected Output in StrictMode:
Even with the dependency array, StrictMode will still log the effect twice during development to confirm it is idempotent and safe. However, the behavior should be consistent. If you see the fetch request firing exactly twice (once per mount) but the data loads correctly without race conditions or duplicate state updates in the UI, the fix is successful.
Illustrative Console Log:
Fetching data for user ID: 101
Fetching data for user ID: 101
Cleanup: Unmounting UserProfile component
Cleanup: Unmounting UserProfile component
Notice that the logs appear in pairs. This is expected behavior in StrictMode. The key difference from the previous state is that the side effect (the fetch) is now strictly bound to the lifecycle of the userId prop value, preventing runaway loops caused by stale closures or missing dependencies.
Common Mistakes and Fixes
Developers often encounter specific pitfalls when dealing with useEffect in StrictMode:
- Mistake: Using
useEffectfor initial state setting.- Fix: Use the functional state update pattern (
setUser(prev => ...)). This ensures you don’t rely on stale closures inside the effect, which can cause updates to be skipped or applied out of order.
- Fix: Use the functional state update pattern (
- Mistake: Missing dependencies in the array.
- Fix: If a variable is used inside the effect but not listed in the dependency array, React cannot guarantee the effect runs when that variable changes. Use
useEffectdebugger tools or ESLint rules (likeeslint-plugin-react-hooks) to catch these automatically.
- Fix: If a variable is used inside the effect but not listed in the dependency array, React cannot guarantee the effect runs when that variable changes. Use
- Mistake: Performing DOM manipulation directly.
- Fix: Avoid accessing
document.getElementByIdinside effects if possible. Instead, use refs (useRef) which persist across renders without triggering re-renders, keeping the effect logic pure.
- Fix: Avoid accessing
Student Practice Task and Industry Application
To solidify understanding, engage in the following practice task:
Student Task: Create a component that toggles a “dark mode” class on the document.body.
1. Implement the toggle logic using a state variable isDarkMode.
2. Initially, you might write the effect without dependencies to run it whenever the toggle button is clicked (via state change).
3. Add StrictMode and observe warnings if the effect runs too frequently or doesn’t clean up the class when toggling back.
4. Refactor to ensure the effect only adds/removes the class when isDarkMode changes, and returns a cleanup function that removes the class if the component unmounts (though in this specific case, managing the global body class requires careful ref management).
Industry Application: In a production API integration project, imagine you are building a real-time chat widget. The widget connects to a WebSocket server. If the useEffect managing the connection lacks proper cleanup or dependency tracking, the socket might stay open even after the user closes the tab, causing memory leaks in the browser context. StrictMode helps catch these leaks early by forcing double-mounting, revealing if the cleanup function is actually being invoked. Always verify your cleanup logic handles both standard unmounts and component re-renders with prop changes.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

