Sub topic 11
Initialize the app once without an Effect
This chapter assumes you know function components, useState, and the basics of useEffect with a dependency array. You should also know that React in development can render and mount components more than once on purpose.
The problem: "once per app load" is not "once per mount"
Some work should happen once when the application starts. Examples are reading a saved auth token, loading settings from localStorage, or configuring an analytics library. A common first attempt is an Effect with an empty dependency array:
import { useEffect } from 'react';
function App() {
useEffect(() => {
loadDataFromLocalStorage();
checkAuthToken();
}, []);
return <main>My app</main>;
}An empty array means "run after this component mounts". It does not mean "run once per page load". Two things break that assumption:
- In development, Strict Mode mounts each component, unmounts it, and mounts it again. This checks that your Effects clean up correctly. Your initialization runs twice.
- If
Appis ever unmounted and mounted again, for example by a parent that swaps it out or by Fast Refresh, the Effect runs again.
For most initialization, running twice is harmless. For some it is not. A token check that invalidates a one-time token is one example. Another is an analytics call that records a duplicate event.
Why an Effect is the wrong tool here
An Effect synchronizes a component with an outside system for as long as the component is on screen. It starts that synchronization on mount and stops it on cleanup. Application startup is different. It has no matching "stop" step and belongs to the page load, not to one component's lifetime. React's re-run behavior is designed for synchronization, so it is a poor fit for this job.
Option 1: a module-level guard
Keep a variable outside the component. It lives as long as the module does, so it survives remounts.
import { useEffect } from 'react';
let didInit = false;
function loadDataFromLocalStorage() {
console.log('Loaded saved settings');
}
function checkAuthToken() {
console.log('Checked auth token');
}
export default function App() {
useEffect(() => {
if (!didInit) {
didInit = true;
loadDataFromLocalStorage();
checkAuthToken();
}
}, []);
return <main>My app</main>;
}The console prints each message once, even in Strict Mode. The Effect still runs twice, but the guard turns the second run into a no-op. This option keeps the code inside the component tree. It also runs only in the browser, because Effects do not run during server rendering.
Option 2: run it at the top level of the entry module
If the work does not need anything from a component, run it when the module loads. React's guidance is to guard it with a browser check if the file may also run on a server.
import { createRoot } from 'react-dom/client';
function loadDataFromLocalStorage() {
console.log('Loaded saved settings');
}
function checkAuthToken() {
console.log('Checked auth token');
}
if (typeof window !== 'undefined') {
checkAuthToken();
loadDataFromLocalStorage();
}
function App() {
return <main>My app</main>;
}
createRoot(document.getElementById('root')).render(<App />);This code runs before the first render, once per page load. It is also easy to find, because it sits at the start of your app's entry file.
Choosing between them
| Situation | Use |
|---|---|
| Work must run once per page load and needs no component state | Top-level code in the entry module |
| You want it next to the component, or it must be browser-only | Module-level guard in an Effect |
| It connects to something and must disconnect later | A normal Effect with cleanup |
Exercises
Exercise
A teammate wraps checkAuthToken() in useEffect(..., []) and sees it log twice in development. They say the bug is in React. What is actually happening, and what are two ways to make it run once?
Show answer
Strict Mode mounts, unmounts, and remounts the component in development to test Effect cleanup, so the empty-array Effect runs twice. To run it once, either put a module-level didInit guard inside the Effect, or call checkAuthToken() at the top level of the entry module, guarded by typeof window !== 'undefined' if the file may run on a server.
Exercise
Should a WebSocket connection that the chat screen needs be opened with a didInit guard? Explain.
Show answer
No. The connection belongs to the chat screen's lifetime, so it should be opened in an Effect and closed in that Effect's cleanup function. A guard would hide the missing cleanup and could leave the connection open after the screen unmounts.