xonecas.io
556
Bn

bees-nest / files

bees-nest / .opencode / skills / vercel-react-best-practices / rules / advanced-init-once.md

958 bytes
1---
2title: Initialize App Once, Not Per Mount
3impact: LOW-MEDIUM
4impactDescription: avoids duplicate init in development
5tags: initialization, useEffect, app-startup, side-effects
6---
7
8## Initialize App Once, Not Per Mount
9
10Do 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
15function Comp() {
16  useEffect(() => {
17    loadFromStorage()
18    checkAuthToken()
19  }, [])
20
21  // ...
22}
23```
24
25**Correct (once per app load):**
26
27```tsx
28let didInit = false
29
30function Comp() {
31  useEffect(() => {
32    if (didInit) return
33    didInit = true
34    loadFromStorage()
35    checkAuthToken()
36  }, [])
37
38  // ...
39}
40```
41
42Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)