Sub topic 11
Initialize the App Once Without an Effect
What this chapter assumes
You should know how useState and props work, and you should have used useEffect with a dependency array. You should also know that a component can mount, unmount, and mount again during its life. The earlier chapters in this tutorial argued that Effects are for synchronizing with external systems. This chapter covers a case that looks like a fit for an Effect but often is not: code that must run once when the whole app loads.
The problem: once per app load, not once per mount
Some logic belongs to the application, not to a component. Typical examples:
- Reading a saved auth token from
localStorageand validating it. - Loading user preferences into a store.
- Configuring an analytics or error-reporting library.
- Registering a global handler or polyfill.
The usual first attempt is an Effect with an empty dependency array, placed in the top-level component:
import { useEffect } from 'react';
function loadDataFromLocalStorage() {
console.log('Loading saved data');
}
function checkAuthToken() {
console.log('Checking auth token');
}
function App() {
useEffect(() => {
loadDataFromLocalStorage();
checkAuthToken();
}, []);
return <h1>Dashboard</h1>;
}
export default App;An empty array means "run after this component mounts". It does not mean "run once per page load". The Effect runs once per mount, and a component can mount more than once.
Why the empty-array Effect runs more than once
There are two ways the Effect above runs again.
Strict Mode in development. In development, <StrictMode> mounts each component, immediately unmounts it, and mounts it again. React does this to check that your Effects clean up properly. With the Effect above, you see both log lines twice. Production builds do not do this.
Real remounts. Any component can be unmounted and mounted again in production. A parent might render it conditionally, a route change might replace it, or a changed key might reset it. If App is ever remounted, the Effect runs again. The same applies to features that hide and restore UI. React may add more such features, so you should not rely on a component mounting exactly once.
For many init tasks, running twice is harmless. Reading localStorage twice does no damage. For others it causes real problems: validating a one-time token twice, sending a duplicate analytics event, or registering a handler twice. If you cannot tell whether your init code is safe to run twice, treat it as unsafe.
The first fix is to ask whether it is an Effect at all
An Effect keeps a component in sync with something while that component is on screen. It has a setup and, ideally, a cleanup. App initialization has no cleanup and is not tied to any component's lifetime. It is a one-time step that happens before or alongside the first render.
That mismatch is the signal. When code has no natural cleanup and belongs to the app rather than a component, you can usually move it out of the component. Two patterns work.
Option 1: a module-level guard variable
Keep the code in the Effect, but track whether it has already run using a variable at module scope:
import { useEffect } from 'react';
let didInit = false;
function loadDataFromLocalStorage() {
console.log('Loading saved data');
}
function checkAuthToken() {
console.log('Checking auth token');
}
function App() {
useEffect(() => {
if (!didInit) {
didInit = true;
loadDataFromLocalStorage();
checkAuthToken();
}
}, []);
return <h1>Dashboard</h1>;
}
export default App;A module is evaluated once per page load, so didInit lives as long as the page does. When Strict Mode remounts App, the second run of the Effect sees didInit === true and skips the work. The same happens after any real remount.
This pattern is a small change to existing code, and the init still runs after the first render. That matters if the init needs the DOM, since Effects run after the browser can paint.
The guard has limits:
- It lives in module state, so tests that import the module share it. A second test may see
didInitalreadytrue. - During development, Fast Refresh may re-evaluate the module and reset the variable, so the init can run again after an edit. That is normal.
- A page reload resets everything, which is what "once per app load" means.
Option 2: run it at module top level
If the init does not need React or the DOM, you can drop the Effect and run it when the module is first imported. The natural place is the entry file:
// init.js
export function checkAuthToken() {
const token = localStorage.getItem('authToken');
console.log(token ? 'Token found' : 'No token');
}
export function loadDataFromLocalStorage() {
const raw = localStorage.getItem('savedData');
console.log(raw ? 'Saved data loaded' : 'No saved data');
}// index.js
import { createRoot } from 'react-dom/client';
import App from './App';
import { checkAuthToken, loadDataFromLocalStorage } from './init';
if (typeof window !== 'undefined') {
checkAuthToken();
loadDataFromLocalStorage();
}
createRoot(document.getElementById('root')).render(<App />);The code runs once, before the first render, and does not depend on how many times React mounts anything. Strict Mode cannot double it, because Strict Mode only affects component rendering and Effects.
The typeof window !== 'undefined' check protects against environments without a browser. If the same module is imported during server rendering or in a Node-based test, window and localStorage do not exist, and the call would throw a ReferenceError. A plain client-only entry point like the one above does not strictly need the check. Frameworks that import your root module on the server do.
Choosing between the options
| Situation | Where it goes |
|---|---|
| Needs to run once per page load, needs no DOM or React | Module top level in the entry file, guarded for non-browser environments |
| Needs to run once per page load, but should run after the first render | Effect with a module-level `didInit` guard |
| Must run each time a specific component appears and be undone when it leaves | A normal Effect with cleanup |
| Must run when the user does something, such as submitting a form | An event handler |
| Needs to react to a value changing, such as a `userId` | An Effect with that value in its dependency array, or a different pattern from earlier chapters |
| Needs to run once per server request in a framework | The framework's own mechanism, not a module variable |
The last row deserves a note. A module variable is shared by everything that runs in that process. On a server, that process handles many users. A guard like didInit would run init for the first request and skip it for every later one. Init that must happen per request, or that touches per-user data, must not use this pattern.
A realistic walkthrough
Suppose your app must restore a saved theme before the first paint to avoid a flash of the wrong colors. Walk through the options:
- An Effect with
[]runs after paint. The user sees the default theme for a moment, then it switches. That is the flash you wanted to avoid, and in development it also runs twice. - A module-level guard still runs after paint, so the flash remains. It fixes the double run but not the timing.
- Top-level code in
index.jsruns beforecreateRoot(...).render(...). You can set the theme ondocument.documentElementfirst, so the first paint is already correct.
// index.js
import { createRoot } from 'react-dom/client';
import App from './App';
function applySavedTheme() {
const theme = localStorage.getItem('theme') || 'light';
document.documentElement.dataset.theme = theme;
}
if (typeof window !== 'undefined') {
applySavedTheme();
}
createRoot(document.getElementById('root')).render(<App />);The right pattern depends on when the work must happen, not only on how many times.
Common errors
- Assuming
[]means once per app. It means once per mount. Strict Mode and remounts both break the assumption. - Silencing Strict Mode to hide the double run. Removing
<StrictMode>makes the symptom vanish in development. The cause is still there in production remounts. Fix the code instead. - Initializing with an Effect that has no cleanup but real side effects. If the init registers a listener, subscribes, or starts a timer, it needs cleanup and is a real Effect. Write the cleanup. A guard variable would leave the listener alive forever.
- Putting per-user work in module scope on a server. Module state is shared across requests, so one user's data can leak into another's. Per-user init does not belong there.
- Doing heavy work at import time. Top-level code blocks the first render. If it is slow, run it after the first render, or fetch it asynchronously.
- Forgetting that tests share module state. If a guard variable stops your init from running in later tests, reset the modules between tests or export a small reset function for tests.
Exercise
A teammate wrote useEffect(() => { analytics.init(); }, []); in App. Analytics reports two "init" events per page load in development but one in production. Explain why, and name two ways to make it run once in development as well. Which would you choose if analytics.init() does not need the DOM?
Show answer
In development, Strict Mode mounts App, unmounts it, and mounts it again, so the Effect runs twice. Production does not do this check, so it runs once (although a real remount would run it again). You can fix it with a module-level guard (let didInit = false; and an if (!didInit) { didInit = true; analytics.init(); } check inside the Effect), or by calling analytics.init() at module top level in the entry file, guarded with typeof window !== 'undefined' if the module may be imported outside a browser. If analytics.init() does not need the DOM or the first render, choose the top-level call. It runs once per page load before any rendering, and it does not depend on how many times React mounts a component.
Exercise
Your app's init code calls window.addEventListener('resize', handleResize). A colleague suggests a didInit guard so it only registers once. Why is that the wrong tool, and what should you do instead?
Show answer
Registering a listener is a subscription that needs cleanup, so it is a real Effect, not one-time app initialization. A guard would keep the listener registered even if the component unmounts, and it would hide the missing cleanup. Write an Effect that adds the listener and returns a cleanup function that calls window.removeEventListener('resize', handleResize). Strict Mode's extra mount then confirms that setup, cleanup, and setup again leave exactly one listener active.