返回 AiToEarn
advanced-init-once.md
1 ---
2 title: Initialize App Once, Not Per Mount
3 impact: LOW-MEDIUM
4 impactDescription: avoids duplicate init in development
5 tags: initialization, useEffect, app-startup, side-effects
6 ---
7
8 ## Initialize App Once, Not Per Mount
9
10 Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
11
12 **Incorrect (runs twice in dev, re-runs on remount):**
13
14 ```tsx
15 function Comp() {
16 useEffect(() => {
17 loadFromStorage()
18 checkAuthToken()
19 }, [])
20
21 // ...
22 }
23 ```
24
25 **Correct (once per app load):**
26
27 ```tsx
28 let didInit = false
29
30 function Comp() {
31 useEffect(() => {
32 if (didInit) return
33 didInit = true
34 loadFromStorage()
35 checkAuthToken()
36 }, [])
37
38 // ...
39 }
40 ```
41
42 Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
43
43 lines MARKDOWN