summaryrefslogtreecommitdiff
path: root/packages/react-best-practices-build/test-cases.json
blob: 02ce981ed69c4f05db8389c06748b851b4677443 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
[
  {
    "ruleId": "",
    "ruleTitle": "Do Not Put Effect Events in Dependency Arrays",
    "type": "bad",
    "code": "import { useEffect, useEffectEvent } from 'react'\n\nfunction ChatRoom({ roomId, onConnected }: {\n  roomId: string\n  onConnected: () => void\n}) {\n  const handleConnected = useEffectEvent(onConnected)\n\n  useEffect(() => {\n    const connection = createConnection(roomId)\n    connection.on('connected', handleConnected)\n    connection.connect()\n\n    return () => connection.disconnect()\n  }, [roomId, handleConnected])\n}",
    "language": "tsx",
    "description": "Effect Event added as a dependency"
  },
  {
    "ruleId": "",
    "ruleTitle": "Do Not Put Effect Events in Dependency Arrays",
    "type": "good",
    "code": "import { useEffect, useEffectEvent } from 'react'\n\nfunction ChatRoom({ roomId, onConnected }: {\n  roomId: string\n  onConnected: () => void\n}) {\n  const handleConnected = useEffectEvent(onConnected)\n\n  useEffect(() => {\n    const connection = createConnection(roomId)\n    connection.on('connected', handleConnected)\n    connection.connect()\n\n    return () => connection.disconnect()\n  }, [roomId])\n}",
    "language": "tsx",
    "description": "depend on reactive values, not the Effect Event"
  },
  {
    "ruleId": "",
    "ruleTitle": "Store Event Handlers in Refs",
    "type": "bad",
    "code": "function useWindowEvent(event: string, handler: (e) => void) {\n  useEffect(() => {\n    window.addEventListener(event, handler)\n    return () => window.removeEventListener(event, handler)\n  }, [event, handler])\n}",
    "language": "tsx",
    "description": "re-subscribes on every render"
  },
  {
    "ruleId": "",
    "ruleTitle": "Store Event Handlers in Refs",
    "type": "good",
    "code": "import { useEffectEvent } from 'react'\n\nfunction useWindowEvent(event: string, handler: (e) => void) {\n  const onEvent = useEffectEvent(handler)\n\n  useEffect(() => {\n    window.addEventListener(event, onEvent)\n    return () => window.removeEventListener(event, onEvent)\n  }, [event])\n}",
    "language": "tsx",
    "description": "stable subscription"
  },
  {
    "ruleId": "",
    "ruleTitle": "Initialize App Once, Not Per Mount",
    "type": "bad",
    "code": "function Comp() {\n  useEffect(() => {\n    loadFromStorage()\n    checkAuthToken()\n  }, [])\n\n  // ...\n}",
    "language": "tsx",
    "description": "runs twice in dev, re-runs on remount"
  },
  {
    "ruleId": "",
    "ruleTitle": "Initialize App Once, Not Per Mount",
    "type": "good",
    "code": "let didInit = false\n\nfunction Comp() {\n  useEffect(() => {\n    if (didInit) return\n    didInit = true\n    loadFromStorage()\n    checkAuthToken()\n  }, [])\n\n  // ...\n}",
    "language": "tsx",
    "description": "once per app load"
  },
  {
    "ruleId": "",
    "ruleTitle": "useEffectEvent for Stable Callback Refs",
    "type": "bad",
    "code": "function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {\n  const [query, setQuery] = useState('')\n\n  useEffect(() => {\n    const timeout = setTimeout(() => onSearch(query), 300)\n    return () => clearTimeout(timeout)\n  }, [query, onSearch])\n}",
    "language": "tsx",
    "description": "effect re-runs on every callback change"
  },
  {
    "ruleId": "",
    "ruleTitle": "useEffectEvent for Stable Callback Refs",
    "type": "good",
    "code": "import { useEffectEvent } from 'react';\n\nfunction SearchInput({ onSearch }: { onSearch: (q: string) => void }) {\n  const [query, setQuery] = useState('')\n  const onSearchEvent = useEffectEvent(onSearch)\n\n  useEffect(() => {\n    const timeout = setTimeout(() => onSearchEvent(query), 300)\n    return () => clearTimeout(timeout)\n  }, [query])\n}",
    "language": "tsx",
    "description": "using React's useEffectEvent"
  },
  {
    "ruleId": "",
    "ruleTitle": "Prevent Waterfall Chains in API Routes",
    "type": "bad",
    "code": "export async function GET(request: Request) {\n  const session = await auth()\n  const config = await fetchConfig()\n  const data = await fetchData(session.user.id)\n  return Response.json({ data, config })\n}",
    "language": "typescript",
    "description": "config waits for auth, data waits for both"
  },
  {
    "ruleId": "",
    "ruleTitle": "Prevent Waterfall Chains in API Routes",
    "type": "good",
    "code": "export async function GET(request: Request) {\n  const sessionPromise = auth()\n  const configPromise = fetchConfig()\n  const session = await sessionPromise\n  const [config, data] = await Promise.all([\n    configPromise,\n    fetchData(session.user.id)\n  ])\n  return Response.json({ data, config })\n}",
    "language": "typescript",
    "description": "auth and config start immediately"
  },
  {
    "ruleId": "",
    "ruleTitle": "Check Cheap Conditions Before Async Flags",
    "type": "bad",
    "code": "const someFlag = await getFlag()\n\nif (someFlag && someCondition) {\n  // ...\n}",
    "language": "typescript",
    "description": "Incorrect example for Check Cheap Conditions Before Async Flags"
  },
  {
    "ruleId": "",
    "ruleTitle": "Check Cheap Conditions Before Async Flags",
    "type": "good",
    "code": "if (someCondition) {\n  const someFlag = await getFlag()\n  if (someFlag) {\n    // ...\n  }\n}",
    "language": "typescript",
    "description": "Correct example for Check Cheap Conditions Before Async Flags"
  },
  {
    "ruleId": "",
    "ruleTitle": "Defer Await Until Needed",
    "type": "bad",
    "code": "async function handleRequest(userId: string, skipProcessing: boolean) {\n  const userData = await fetchUserData(userId)\n  \n  if (skipProcessing) {\n    // Returns immediately but still waited for userData\n    return { skipped: true }\n  }\n  \n  // Only this branch uses userData\n  return processUserData(userData)\n}",
    "language": "typescript",
    "description": "blocks both branches"
  },
  {
    "ruleId": "",
    "ruleTitle": "Defer Await Until Needed",
    "type": "good",
    "code": "async function handleRequest(userId: string, skipProcessing: boolean) {\n  if (skipProcessing) {\n    // Returns immediately without waiting\n    return { skipped: true }\n  }\n  \n  // Fetch only when needed\n  const userData = await fetchUserData(userId)\n  return processUserData(userData)\n}",
    "language": "typescript",
    "description": "only blocks when needed"
  },
  {
    "ruleId": "",
    "ruleTitle": "Dependency-Based Parallelization",
    "type": "bad",
    "code": "const [user, config] = await Promise.all([\n  fetchUser(),\n  fetchConfig()\n])\nconst profile = await fetchProfile(user.id)",
    "language": "typescript",
    "description": "profile waits for config unnecessarily"
  },
  {
    "ruleId": "",
    "ruleTitle": "Dependency-Based Parallelization",
    "type": "good",
    "code": "import { all } from 'better-all'\n\nconst { user, config, profile } = await all({\n  async user() { return fetchUser() },\n  async config() { return fetchConfig() },\n  async profile() {\n    return fetchProfile((await this.$.user).id)\n  }\n})",
    "language": "typescript",
    "description": "config and profile run in parallel"
  },
  {
    "ruleId": "",
    "ruleTitle": "Promise.all() for Independent Operations",
    "type": "bad",
    "code": "const user = await fetchUser()\nconst posts = await fetchPosts()\nconst comments = await fetchComments()",
    "language": "typescript",
    "description": "sequential execution, 3 round trips"
  },
  {
    "ruleId": "",
    "ruleTitle": "Promise.all() for Independent Operations",
    "type": "good",
    "code": "const [user, posts, comments] = await Promise.all([\n  fetchUser(),\n  fetchPosts(),\n  fetchComments()\n])",
    "language": "typescript",
    "description": "parallel execution, 1 round trip"
  },
  {
    "ruleId": "",
    "ruleTitle": "Strategic Suspense Boundaries",
    "type": "bad",
    "code": "async function Page() {\n  const data = await fetchData() // Blocks entire page\n  \n  return (\n    <div>\n      <div>Sidebar</div>\n      <div>Header</div>\n      <div>\n        <DataDisplay data={data} />\n      </div>\n      <div>Footer</div>\n    </div>\n  )\n}",
    "language": "tsx",
    "description": "wrapper blocked by data fetching"
  },
  {
    "ruleId": "",
    "ruleTitle": "Strategic Suspense Boundaries",
    "type": "good",
    "code": "function Page() {\n  return (\n    <div>\n      <div>Sidebar</div>\n      <div>Header</div>\n      <div>\n        <Suspense fallback={<Skeleton />}>\n          <DataDisplay />\n        </Suspense>\n      </div>\n      <div>Footer</div>\n    </div>\n  )\n}\n\nasync function DataDisplay() {\n  const data = await fetchData() // Only blocks this component\n  return <div>{data.content}</div>\n}",
    "language": "tsx",
    "description": "wrapper shows immediately, data streams in"
  },
  {
    "ruleId": "",
    "ruleTitle": "Prefer Statically Analyzable Paths",
    "type": "bad",
    "code": "const PAGE_MODULES = {\n  home: './pages/home',\n  settings: './pages/settings',\n} as const\n\nconst Page = await import(PAGE_MODULES[pageName])",
    "language": "ts",
    "description": "the bundler cannot tell what may be imported"
  },
  {
    "ruleId": "",
    "ruleTitle": "Prefer Statically Analyzable Paths",
    "type": "good",
    "code": "const PAGE_MODULES = {\n  home: () => import('./pages/home'),\n  settings: () => import('./pages/settings'),\n} as const\n\nconst Page = await PAGE_MODULES[pageName]()",
    "language": "ts",
    "description": "use an explicit map of allowed modules"
  },
  {
    "ruleId": "",
    "ruleTitle": "Prefer Statically Analyzable Paths",
    "type": "bad",
    "code": "const baseDir = path.join(process.cwd(), 'content/' + contentKind)",
    "language": "ts",
    "description": "a 2-value enum still hides the final path from static analysis"
  },
  {
    "ruleId": "",
    "ruleTitle": "Prefer Statically Analyzable Paths",
    "type": "good",
    "code": "const baseDir =\n  kind === ContentKind.Blog\n    ? path.join(process.cwd(), 'content/blog')\n    : path.join(process.cwd(), 'content/docs')",
    "language": "ts",
    "description": "make each final path literal at the callsite"
  },
  {
    "ruleId": "",
    "ruleTitle": "Avoid Barrel File Imports",
    "type": "bad",
    "code": "import { Check, X, Menu } from 'lucide-react'\n// Loads 1,583 modules, takes ~2.8s extra in dev\n// Runtime cost: 200-800ms on every cold start\n\nimport { Button, TextField } from '@mui/material'\n// Loads 2,225 modules, takes ~4.2s extra in dev",
    "language": "tsx",
    "description": "imports entire library"
  },
  {
    "ruleId": "",
    "ruleTitle": "Avoid Barrel File Imports",
    "type": "good",
    "code": "// Keep the standard imports - Next.js transforms them to direct imports\nimport { Check, X, Menu } from 'lucide-react'\n// Full TypeScript support, no manual path wrangling",
    "language": "tsx",
    "description": "Correct - Next.js 13.5+ (recommended) example for Avoid Barrel File Imports"
  },
  {
    "ruleId": "",
    "ruleTitle": "Avoid Barrel File Imports",
    "type": "good",
    "code": "import Button from '@mui/material/Button'\nimport TextField from '@mui/material/TextField'\n// Loads only what you use",
    "language": "tsx",
    "description": "Correct - Direct imports (non-Next.js projects) example for Avoid Barrel File Imports"
  },
  {
    "ruleId": "",
    "ruleTitle": "Defer Non-Critical Third-Party Libraries",
    "type": "bad",
    "code": "import { Analytics } from '@vercel/analytics/react'\n\nexport default function RootLayout({ children }) {\n  return (\n    <html>\n      <body>\n        {children}\n        <Analytics />\n      </body>\n    </html>\n  )\n}",
    "language": "tsx",
    "description": "blocks initial bundle"
  },
  {
    "ruleId": "",
    "ruleTitle": "Defer Non-Critical Third-Party Libraries",
    "type": "good",
    "code": "import dynamic from 'next/dynamic'\n\nconst Analytics = dynamic(\n  () => import('@vercel/analytics/react').then(m => m.Analytics),\n  { ssr: false }\n)\n\nexport default function RootLayout({ children }) {\n  return (\n    <html>\n      <body>\n        {children}\n        <Analytics />\n      </body>\n    </html>\n  )\n}",
    "language": "tsx",
    "description": "loads after hydration"
  },
  {
    "ruleId": "",
    "ruleTitle": "Dynamic Imports for Heavy Components",
    "type": "bad",
    "code": "import { MonacoEditor } from './monaco-editor'\n\nfunction CodePanel({ code }: { code: string }) {\n  return <MonacoEditor value={code} />\n}",
    "language": "tsx",
    "description": "Monaco bundles with main chunk ~300KB"
  },
  {
    "ruleId": "",
    "ruleTitle": "Dynamic Imports for Heavy Components",
    "type": "good",
    "code": "import dynamic from 'next/dynamic'\n\nconst MonacoEditor = dynamic(\n  () => import('./monaco-editor').then(m => m.MonacoEditor),\n  { ssr: false }\n)\n\nfunction CodePanel({ code }: { code: string }) {\n  return <MonacoEditor value={code} />\n}",
    "language": "tsx",
    "description": "Monaco loads on demand"
  },
  {
    "ruleId": "",
    "ruleTitle": "Deduplicate Global Event Listeners",
    "type": "bad",
    "code": "function useKeyboardShortcut(key: string, callback: () => void) {\n  useEffect(() => {\n    const handler = (e: KeyboardEvent) => {\n      if (e.metaKey && e.key === key) {\n        callback()\n      }\n    }\n    window.addEventListener('keydown', handler)\n    return () => window.removeEventListener('keydown', handler)\n  }, [key, callback])\n}",
    "language": "tsx",
    "description": "N instances = N listeners"
  },
  {
    "ruleId": "",
    "ruleTitle": "Deduplicate Global Event Listeners",
    "type": "good",
    "code": "import useSWRSubscription from 'swr/subscription'\n\n// Module-level Map to track callbacks per key\nconst keyCallbacks = new Map<string, Set<() => void>>()\n\nfunction useKeyboardShortcut(key: string, callback: () => void) {\n  // Register this callback in the Map\n  useEffect(() => {\n    if (!keyCallbacks.has(key)) {\n      keyCallbacks.set(key, new Set())\n    }\n    keyCallbacks.get(key)!.add(callback)\n\n    return () => {\n      const set = keyCallbacks.get(key)\n      if (set) {\n        set.delete(callback)\n        if (set.size === 0) {\n          keyCallbacks.delete(key)\n        }\n      }\n    }\n  }, [key, callback])\n\n  useSWRSubscription('global-keydown', () => {\n    const handler = (e: KeyboardEvent) => {\n      if (e.metaKey && keyCallbacks.has(e.key)) {\n        keyCallbacks.get(e.key)!.forEach(cb => cb())\n      }\n    }\n    window.addEventListener('keydown', handler)\n    return () => window.removeEventListener('keydown', handler)\n  })\n}\n\nfunction Profile() {\n  // Multiple shortcuts will share the same listener\n  useKeyboardShortcut('p', () => { /* ... */ }) \n  useKeyboardShortcut('k', () => { /* ... */ })\n  // ...\n}",
    "language": "tsx",
    "description": "N instances = 1 listener"
  },
  {
    "ruleId": "",
    "ruleTitle": "Version and Minimize localStorage Data",
    "type": "bad",
    "code": "// No version, stores everything, no error handling\nlocalStorage.setItem('userConfig', JSON.stringify(fullUserObject))\nconst data = localStorage.getItem('userConfig')",
    "language": "typescript",
    "description": "Incorrect example for Version and Minimize localStorage Data"
  },
  {
    "ruleId": "",
    "ruleTitle": "Version and Minimize localStorage Data",
    "type": "good",
    "code": "const VERSION = 'v2'\n\nfunction saveConfig(config: { theme: string; language: string }) {\n  try {\n    localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))\n  } catch {\n    // Throws in incognito/private browsing, quota exceeded, or disabled\n  }\n}\n\nfunction loadConfig() {\n  try {\n    const data = localStorage.getItem(`userConfig:${VERSION}`)\n    return data ? JSON.parse(data) : null\n  } catch {\n    return null\n  }\n}\n\n// Migration from v1 to v2\nfunction migrate() {\n  try {\n    const v1 = localStorage.getItem('userConfig:v1')\n    if (v1) {\n      const old = JSON.parse(v1)\n      saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })\n      localStorage.removeItem('userConfig:v1')\n    }\n  } catch {}\n}",
    "language": "typescript",
    "description": "Correct example for Version and Minimize localStorage Data"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Passive Event Listeners for Scrolling Performance",
    "type": "bad",
    "code": "useEffect(() => {\n  const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)\n  const handleWheel = (e: WheelEvent) => console.log(e.deltaY)\n  \n  document.addEventListener('touchstart', handleTouch)\n  document.addEventListener('wheel', handleWheel)\n  \n  return () => {\n    document.removeEventListener('touchstart', handleTouch)\n    document.removeEventListener('wheel', handleWheel)\n  }\n}, [])",
    "language": "typescript",
    "description": "Incorrect example for Use Passive Event Listeners for Scrolling Performance"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Passive Event Listeners for Scrolling Performance",
    "type": "good",
    "code": "useEffect(() => {\n  const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)\n  const handleWheel = (e: WheelEvent) => console.log(e.deltaY)\n  \n  document.addEventListener('touchstart', handleTouch, { passive: true })\n  document.addEventListener('wheel', handleWheel, { passive: true })\n  \n  return () => {\n    document.removeEventListener('touchstart', handleTouch)\n    document.removeEventListener('wheel', handleWheel)\n  }\n}, [])",
    "language": "typescript",
    "description": "Correct example for Use Passive Event Listeners for Scrolling Performance"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use SWR for Automatic Deduplication",
    "type": "bad",
    "code": "function UserList() {\n  const [users, setUsers] = useState([])\n  useEffect(() => {\n    fetch('/api/users')\n      .then(r => r.json())\n      .then(setUsers)\n  }, [])\n}",
    "language": "tsx",
    "description": "no deduplication, each instance fetches"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use SWR for Automatic Deduplication",
    "type": "good",
    "code": "import useSWR from 'swr'\n\nfunction UserList() {\n  const { data: users } = useSWR('/api/users', fetcher)\n}",
    "language": "tsx",
    "description": "multiple instances share one request"
  },
  {
    "ruleId": "",
    "ruleTitle": "Avoid Layout Thrashing",
    "type": "bad",
    "code": "function layoutThrashing(element: HTMLElement) {\n  element.style.width = '100px'\n  const width = element.offsetWidth  // Forces reflow\n  element.style.height = '200px'\n  const height = element.offsetHeight  // Forces another reflow\n}",
    "language": "typescript",
    "description": "interleaved reads and writes force reflows"
  },
  {
    "ruleId": "",
    "ruleTitle": "Avoid Layout Thrashing",
    "type": "good",
    "code": "function updateElementStyles(element: HTMLElement) {\n  // Batch all writes together\n  element.style.width = '100px'\n  element.style.height = '200px'\n  element.style.backgroundColor = 'blue'\n  element.style.border = '1px solid black'\n  \n  // Read after all writes are done (single reflow)\n  const { width, height } = element.getBoundingClientRect()\n}",
    "language": "typescript",
    "description": "batch writes, then read once"
  },
  {
    "ruleId": "",
    "ruleTitle": "Avoid Layout Thrashing",
    "type": "good",
    "code": "function updateElementStyles(element: HTMLElement) {\n  element.classList.add('highlighted-box')\n  \n  const { width, height } = element.getBoundingClientRect()\n}",
    "language": "typescript",
    "description": "batch reads, then writes"
  },
  {
    "ruleId": "",
    "ruleTitle": "Cache Repeated Function Calls",
    "type": "bad",
    "code": "function ProjectList({ projects }: { projects: Project[] }) {\n  return (\n    <div>\n      {projects.map(project => {\n        // slugify() called 100+ times for same project names\n        const slug = slugify(project.name)\n        \n        return <ProjectCard key={project.id} slug={slug} />\n      })}\n    </div>\n  )\n}",
    "language": "typescript",
    "description": "redundant computation"
  },
  {
    "ruleId": "",
    "ruleTitle": "Cache Repeated Function Calls",
    "type": "good",
    "code": "// Module-level cache\nconst slugifyCache = new Map<string, string>()\n\nfunction cachedSlugify(text: string): string {\n  if (slugifyCache.has(text)) {\n    return slugifyCache.get(text)!\n  }\n  const result = slugify(text)\n  slugifyCache.set(text, result)\n  return result\n}\n\nfunction ProjectList({ projects }: { projects: Project[] }) {\n  return (\n    <div>\n      {projects.map(project => {\n        // Computed only once per unique project name\n        const slug = cachedSlugify(project.name)\n        \n        return <ProjectCard key={project.id} slug={slug} />\n      })}\n    </div>\n  )\n}",
    "language": "typescript",
    "description": "cached results"
  },
  {
    "ruleId": "",
    "ruleTitle": "Cache Property Access in Loops",
    "type": "bad",
    "code": "for (let i = 0; i < arr.length; i++) {\n  process(obj.config.settings.value)\n}",
    "language": "typescript",
    "description": "3 lookups × N iterations"
  },
  {
    "ruleId": "",
    "ruleTitle": "Cache Property Access in Loops",
    "type": "good",
    "code": "const value = obj.config.settings.value\nconst len = arr.length\nfor (let i = 0; i < len; i++) {\n  process(value)\n}",
    "language": "typescript",
    "description": "1 lookup total"
  },
  {
    "ruleId": "",
    "ruleTitle": "Cache Storage API Calls",
    "type": "bad",
    "code": "function getTheme() {\n  return localStorage.getItem('theme') ?? 'light'\n}\n// Called 10 times = 10 storage reads",
    "language": "typescript",
    "description": "reads storage on every call"
  },
  {
    "ruleId": "",
    "ruleTitle": "Cache Storage API Calls",
    "type": "good",
    "code": "const storageCache = new Map<string, string | null>()\n\nfunction getLocalStorage(key: string) {\n  if (!storageCache.has(key)) {\n    storageCache.set(key, localStorage.getItem(key))\n  }\n  return storageCache.get(key)\n}\n\nfunction setLocalStorage(key: string, value: string) {\n  localStorage.setItem(key, value)\n  storageCache.set(key, value)  // keep cache in sync\n}",
    "language": "typescript",
    "description": "Map cache"
  },
  {
    "ruleId": "",
    "ruleTitle": "Combine Multiple Array Iterations",
    "type": "bad",
    "code": "const admins = users.filter(u => u.isAdmin)\nconst testers = users.filter(u => u.isTester)\nconst inactive = users.filter(u => !u.isActive)",
    "language": "typescript",
    "description": "3 iterations"
  },
  {
    "ruleId": "",
    "ruleTitle": "Combine Multiple Array Iterations",
    "type": "good",
    "code": "const admins: User[] = []\nconst testers: User[] = []\nconst inactive: User[] = []\n\nfor (const user of users) {\n  if (user.isAdmin) admins.push(user)\n  if (user.isTester) testers.push(user)\n  if (!user.isActive) inactive.push(user)\n}",
    "language": "typescript",
    "description": "1 iteration"
  },
  {
    "ruleId": "",
    "ruleTitle": "Early Return from Functions",
    "type": "bad",
    "code": "function validateUsers(users: User[]) {\n  let hasError = false\n  let errorMessage = ''\n  \n  for (const user of users) {\n    if (!user.email) {\n      hasError = true\n      errorMessage = 'Email required'\n    }\n    if (!user.name) {\n      hasError = true\n      errorMessage = 'Name required'\n    }\n    // Continues checking all users even after error found\n  }\n  \n  return hasError ? { valid: false, error: errorMessage } : { valid: true }\n}",
    "language": "typescript",
    "description": "processes all items even after finding answer"
  },
  {
    "ruleId": "",
    "ruleTitle": "Early Return from Functions",
    "type": "good",
    "code": "function validateUsers(users: User[]) {\n  for (const user of users) {\n    if (!user.email) {\n      return { valid: false, error: 'Email required' }\n    }\n    if (!user.name) {\n      return { valid: false, error: 'Name required' }\n    }\n  }\n\n  return { valid: true }\n}",
    "language": "typescript",
    "description": "returns immediately on first error"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use flatMap to Map and Filter in One Pass",
    "type": "bad",
    "code": "const userNames = users\n  .map(user => user.isActive ? user.name : null)\n  .filter(Boolean)",
    "language": "typescript",
    "description": "2 iterations, intermediate array"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use flatMap to Map and Filter in One Pass",
    "type": "good",
    "code": "const userNames = users.flatMap(user =>\n  user.isActive ? [user.name] : []\n)",
    "language": "typescript",
    "description": "1 iteration, no intermediate array"
  },
  {
    "ruleId": "",
    "ruleTitle": "Hoist RegExp Creation",
    "type": "bad",
    "code": "function Highlighter({ text, query }: Props) {\n  const regex = new RegExp(`(${query})`, 'gi')\n  const parts = text.split(regex)\n  return <>{parts.map((part, i) => ...)}</>\n}",
    "language": "tsx",
    "description": "new RegExp every render"
  },
  {
    "ruleId": "",
    "ruleTitle": "Hoist RegExp Creation",
    "type": "good",
    "code": "const EMAIL_REGEX = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nfunction Highlighter({ text, query }: Props) {\n  const regex = useMemo(\n    () => new RegExp(`(${escapeRegex(query)})`, 'gi'),\n    [query]\n  )\n  const parts = text.split(regex)\n  return <>{parts.map((part, i) => ...)}</>\n}",
    "language": "tsx",
    "description": "memoize or hoist"
  },
  {
    "ruleId": "",
    "ruleTitle": "Build Index Maps for Repeated Lookups",
    "type": "bad",
    "code": "function processOrders(orders: Order[], users: User[]) {\n  return orders.map(order => ({\n    ...order,\n    user: users.find(u => u.id === order.userId)\n  }))\n}",
    "language": "typescript",
    "description": "Incorrect (O(n) per lookup) example for Build Index Maps for Repeated Lookups"
  },
  {
    "ruleId": "",
    "ruleTitle": "Build Index Maps for Repeated Lookups",
    "type": "good",
    "code": "function processOrders(orders: Order[], users: User[]) {\n  const userById = new Map(users.map(u => [u.id, u]))\n\n  return orders.map(order => ({\n    ...order,\n    user: userById.get(order.userId)\n  }))\n}",
    "language": "typescript",
    "description": "Correct (O(1) per lookup) example for Build Index Maps for Repeated Lookups"
  },
  {
    "ruleId": "",
    "ruleTitle": "Early Length Check for Array Comparisons",
    "type": "bad",
    "code": "function hasChanges(current: string[], original: string[]) {\n  // Always sorts and joins, even when lengths differ\n  return current.sort().join() !== original.sort().join()\n}",
    "language": "typescript",
    "description": "always runs expensive comparison"
  },
  {
    "ruleId": "",
    "ruleTitle": "Early Length Check for Array Comparisons",
    "type": "good",
    "code": "function hasChanges(current: string[], original: string[]) {\n  // Early return if lengths differ\n  if (current.length !== original.length) {\n    return true\n  }\n  // Only sort when lengths match\n  const currentSorted = current.toSorted()\n  const originalSorted = original.toSorted()\n  for (let i = 0; i < currentSorted.length; i++) {\n    if (currentSorted[i] !== originalSorted[i]) {\n      return true\n    }\n  }\n  return false\n}",
    "language": "typescript",
    "description": "Correct (O(1) length check first) example for Early Length Check for Array Comparisons"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Loop for Min/Max Instead of Sort",
    "type": "bad",
    "code": "interface Project {\n  id: string\n  name: string\n  updatedAt: number\n}\n\nfunction getLatestProject(projects: Project[]) {\n  const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)\n  return sorted[0]\n}",
    "language": "typescript",
    "description": "Incorrect (O(n log n) - sort to find latest) example for Use Loop for Min/Max Instead of Sort"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Loop for Min/Max Instead of Sort",
    "type": "bad",
    "code": "function getOldestAndNewest(projects: Project[]) {\n  const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)\n  return { oldest: sorted[0], newest: sorted[sorted.length - 1] }\n}",
    "language": "typescript",
    "description": "Incorrect (O(n log n) - sort for oldest and newest) example for Use Loop for Min/Max Instead of Sort"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Loop for Min/Max Instead of Sort",
    "type": "good",
    "code": "function getLatestProject(projects: Project[]) {\n  if (projects.length === 0) return null\n  \n  let latest = projects[0]\n  \n  for (let i = 1; i < projects.length; i++) {\n    if (projects[i].updatedAt > latest.updatedAt) {\n      latest = projects[i]\n    }\n  }\n  \n  return latest\n}\n\nfunction getOldestAndNewest(projects: Project[]) {\n  if (projects.length === 0) return { oldest: null, newest: null }\n  \n  let oldest = projects[0]\n  let newest = projects[0]\n  \n  for (let i = 1; i < projects.length; i++) {\n    if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]\n    if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]\n  }\n  \n  return { oldest, newest }\n}",
    "language": "typescript",
    "description": "Correct (O(n) - single loop) example for Use Loop for Min/Max Instead of Sort"
  },
  {
    "ruleId": "",
    "ruleTitle": "Defer Non-Critical Work with requestIdleCallback",
    "type": "bad",
    "code": "function handleSearch(query: string) {\n  const results = searchItems(query)\n  setResults(results)\n\n  // These block the main thread immediately\n  analytics.track('search', { query })\n  saveToRecentSearches(query)\n  prefetchTopResults(results.slice(0, 3))\n}",
    "language": "typescript",
    "description": "blocks main thread during user interaction"
  },
  {
    "ruleId": "",
    "ruleTitle": "Defer Non-Critical Work with requestIdleCallback",
    "type": "good",
    "code": "function handleSearch(query: string) {\n  const results = searchItems(query)\n  setResults(results)\n\n  // Defer non-critical work to idle periods\n  requestIdleCallback(() => {\n    analytics.track('search', { query })\n  })\n\n  requestIdleCallback(() => {\n    saveToRecentSearches(query)\n  })\n\n  requestIdleCallback(() => {\n    prefetchTopResults(results.slice(0, 3))\n  })\n}",
    "language": "typescript",
    "description": "defers non-critical work to idle time"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Set/Map for O(1) Lookups",
    "type": "bad",
    "code": "const allowedIds = ['a', 'b', 'c', ...]\nitems.filter(item => allowedIds.includes(item.id))",
    "language": "typescript",
    "description": "Incorrect (O(n) per check) example for Use Set/Map for O(1) Lookups"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Set/Map for O(1) Lookups",
    "type": "good",
    "code": "const allowedIds = new Set(['a', 'b', 'c', ...])\nitems.filter(item => allowedIds.has(item.id))",
    "language": "typescript",
    "description": "Correct (O(1) per check) example for Use Set/Map for O(1) Lookups"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use toSorted() Instead of sort() for Immutability",
    "type": "bad",
    "code": "function UserList({ users }: { users: User[] }) {\n  // Mutates the users prop array!\n  const sorted = useMemo(\n    () => users.sort((a, b) => a.name.localeCompare(b.name)),\n    [users]\n  )\n  return <div>{sorted.map(renderUser)}</div>\n}",
    "language": "typescript",
    "description": "mutates original array"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use toSorted() Instead of sort() for Immutability",
    "type": "good",
    "code": "function UserList({ users }: { users: User[] }) {\n  // Creates new sorted array, original unchanged\n  const sorted = useMemo(\n    () => users.toSorted((a, b) => a.name.localeCompare(b.name)),\n    [users]\n  )\n  return <div>{sorted.map(renderUser)}</div>\n}",
    "language": "typescript",
    "description": "creates new array"
  },
  {
    "ruleId": "",
    "ruleTitle": "Animate SVG Wrapper Instead of SVG Element",
    "type": "bad",
    "code": "function LoadingSpinner() {\n  return (\n    <svg \n      className=\"animate-spin\"\n      width=\"24\" \n      height=\"24\" \n      viewBox=\"0 0 24 24\"\n    >\n      <circle cx=\"12\" cy=\"12\" r=\"10\" stroke=\"currentColor\" />\n    </svg>\n  )\n}",
    "language": "tsx",
    "description": "animating SVG directly - no hardware acceleration"
  },
  {
    "ruleId": "",
    "ruleTitle": "Animate SVG Wrapper Instead of SVG Element",
    "type": "good",
    "code": "function LoadingSpinner() {\n  return (\n    <div className=\"animate-spin\">\n      <svg \n        width=\"24\" \n        height=\"24\" \n        viewBox=\"0 0 24 24\"\n      >\n        <circle cx=\"12\" cy=\"12\" r=\"10\" stroke=\"currentColor\" />\n      </svg>\n    </div>\n  )\n}",
    "language": "tsx",
    "description": "animating wrapper div - hardware accelerated"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Explicit Conditional Rendering",
    "type": "bad",
    "code": "function Badge({ count }: { count: number }) {\n  return (\n    <div>\n      {count && <span className=\"badge\">{count}</span>}\n    </div>\n  )\n}\n\n// When count = 0, renders: <div>0</div>\n// When count = 5, renders: <div><span class=\"badge\">5</span></div>",
    "language": "tsx",
    "description": "renders \"0\" when count is 0"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Explicit Conditional Rendering",
    "type": "good",
    "code": "function Badge({ count }: { count: number }) {\n  return (\n    <div>\n      {count > 0 ? <span className=\"badge\">{count}</span> : null}\n    </div>\n  )\n}\n\n// When count = 0, renders: <div></div>\n// When count = 5, renders: <div><span class=\"badge\">5</span></div>",
    "language": "tsx",
    "description": "renders nothing when count is 0"
  },
  {
    "ruleId": "",
    "ruleTitle": "Hoist Static JSX Elements",
    "type": "bad",
    "code": "function LoadingSkeleton() {\n  return <div className=\"animate-pulse h-20 bg-gray-200\" />\n}\n\nfunction Container() {\n  return (\n    <div>\n      {loading && <LoadingSkeleton />}\n    </div>\n  )\n}",
    "language": "tsx",
    "description": "recreates element every render"
  },
  {
    "ruleId": "",
    "ruleTitle": "Hoist Static JSX Elements",
    "type": "good",
    "code": "const loadingSkeleton = (\n  <div className=\"animate-pulse h-20 bg-gray-200\" />\n)\n\nfunction Container() {\n  return (\n    <div>\n      {loading && loadingSkeleton}\n    </div>\n  )\n}",
    "language": "tsx",
    "description": "reuses same element"
  },
  {
    "ruleId": "",
    "ruleTitle": "Prevent Hydration Mismatch Without Flickering",
    "type": "bad",
    "code": "function ThemeWrapper({ children }: { children: ReactNode }) {\n  // localStorage is not available on server - throws error\n  const theme = localStorage.getItem('theme') || 'light'\n  \n  return (\n    <div className={theme}>\n      {children}\n    </div>\n  )\n}",
    "language": "tsx",
    "description": "breaks SSR"
  },
  {
    "ruleId": "",
    "ruleTitle": "Prevent Hydration Mismatch Without Flickering",
    "type": "bad",
    "code": "function ThemeWrapper({ children }: { children: ReactNode }) {\n  const [theme, setTheme] = useState('light')\n  \n  useEffect(() => {\n    // Runs after hydration - causes visible flash\n    const stored = localStorage.getItem('theme')\n    if (stored) {\n      setTheme(stored)\n    }\n  }, [])\n  \n  return (\n    <div className={theme}>\n      {children}\n    </div>\n  )\n}",
    "language": "tsx",
    "description": "visual flickering"
  },
  {
    "ruleId": "",
    "ruleTitle": "Prevent Hydration Mismatch Without Flickering",
    "type": "good",
    "code": "function ThemeWrapper({ children }: { children: ReactNode }) {\n  return (\n    <>\n      <div id=\"theme-wrapper\">\n        {children}\n      </div>\n      <script\n        dangerouslySetInnerHTML={{\n          __html: `\n            (function() {\n              try {\n                var theme = localStorage.getItem('theme') || 'light';\n                var el = document.getElementById('theme-wrapper');\n                if (el) el.className = theme;\n              } catch (e) {}\n            })();\n          `,\n        }}\n      />\n    </>\n  )\n}",
    "language": "tsx",
    "description": "no flicker, no hydration mismatch"
  },
  {
    "ruleId": "",
    "ruleTitle": "Suppress Expected Hydration Mismatches",
    "type": "bad",
    "code": "function Timestamp() {\n  return <span>{new Date().toLocaleString()}</span>\n}",
    "language": "tsx",
    "description": "known mismatch warnings"
  },
  {
    "ruleId": "",
    "ruleTitle": "Suppress Expected Hydration Mismatches",
    "type": "good",
    "code": "function Timestamp() {\n  return (\n    <span suppressHydrationWarning>\n      {new Date().toLocaleString()}\n    </span>\n  )\n}",
    "language": "tsx",
    "description": "suppress expected mismatch only"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use defer or async on Script Tags",
    "type": "bad",
    "code": "export default function Document() {\n  return (\n    <html>\n      <head>\n        <script src=\"https://example.com/analytics.js\" />\n        <script src=\"/scripts/utils.js\" />\n      </head>\n      <body>{/* content */}</body>\n    </html>\n  )\n}",
    "language": "tsx",
    "description": "blocks rendering"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use defer or async on Script Tags",
    "type": "good",
    "code": "import Script from 'next/script'\n\nexport default function Page() {\n  return (\n    <>\n      <Script src=\"https://example.com/analytics.js\" strategy=\"afterInteractive\" />\n      <Script src=\"/scripts/utils.js\" strategy=\"beforeInteractive\" />\n    </>\n  )\n}",
    "language": "tsx",
    "description": "non-blocking"
  },
  {
    "ruleId": "",
    "ruleTitle": "Optimize SVG Precision",
    "type": "bad",
    "code": "<path d=\"M 10.293847 20.847362 L 30.938472 40.192837\" />",
    "language": "svg",
    "description": "excessive precision"
  },
  {
    "ruleId": "",
    "ruleTitle": "Optimize SVG Precision",
    "type": "good",
    "code": "<path d=\"M 10.3 20.8 L 30.9 40.2\" />",
    "language": "svg",
    "description": "1 decimal place"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use useTransition Over Manual Loading States",
    "type": "bad",
    "code": "function SearchResults() {\n  const [query, setQuery] = useState('')\n  const [results, setResults] = useState([])\n  const [isLoading, setIsLoading] = useState(false)\n\n  const handleSearch = async (value: string) => {\n    setIsLoading(true)\n    setQuery(value)\n    const data = await fetchResults(value)\n    setResults(data)\n    setIsLoading(false)\n  }\n\n  return (\n    <>\n      <input onChange={(e) => handleSearch(e.target.value)} />\n      {isLoading && <Spinner />}\n      <ResultsList results={results} />\n    </>\n  )\n}",
    "language": "tsx",
    "description": "manual loading state"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use useTransition Over Manual Loading States",
    "type": "good",
    "code": "import { useTransition, useState } from 'react'\n\nfunction SearchResults() {\n  const [query, setQuery] = useState('')\n  const [results, setResults] = useState([])\n  const [isPending, startTransition] = useTransition()\n\n  const handleSearch = (value: string) => {\n    setQuery(value) // Update input immediately\n    \n    startTransition(async () => {\n      // Fetch and update results\n      const data = await fetchResults(value)\n      setResults(data)\n    })\n  }\n\n  return (\n    <>\n      <input onChange={(e) => handleSearch(e.target.value)} />\n      {isPending && <Spinner />}\n      <ResultsList results={results} />\n    </>\n  )\n}",
    "language": "tsx",
    "description": "useTransition with built-in pending state"
  },
  {
    "ruleId": "",
    "ruleTitle": "Defer State Reads to Usage Point",
    "type": "bad",
    "code": "function ShareButton({ chatId }: { chatId: string }) {\n  const searchParams = useSearchParams()\n\n  const handleShare = () => {\n    const ref = searchParams.get('ref')\n    shareChat(chatId, { ref })\n  }\n\n  return <button onClick={handleShare}>Share</button>\n}",
    "language": "tsx",
    "description": "subscribes to all searchParams changes"
  },
  {
    "ruleId": "",
    "ruleTitle": "Defer State Reads to Usage Point",
    "type": "good",
    "code": "function ShareButton({ chatId }: { chatId: string }) {\n  const handleShare = () => {\n    const params = new URLSearchParams(window.location.search)\n    const ref = params.get('ref')\n    shareChat(chatId, { ref })\n  }\n\n  return <button onClick={handleShare}>Share</button>\n}",
    "language": "tsx",
    "description": "reads on demand, no subscription"
  },
  {
    "ruleId": "",
    "ruleTitle": "Narrow Effect Dependencies",
    "type": "bad",
    "code": "useEffect(() => {\n  console.log(user.id)\n}, [user])",
    "language": "tsx",
    "description": "re-runs on any user field change"
  },
  {
    "ruleId": "",
    "ruleTitle": "Narrow Effect Dependencies",
    "type": "good",
    "code": "useEffect(() => {\n  console.log(user.id)\n}, [user.id])",
    "language": "tsx",
    "description": "re-runs only when id changes"
  },
  {
    "ruleId": "",
    "ruleTitle": "Calculate Derived State During Rendering",
    "type": "bad",
    "code": "function Form() {\n  const [firstName, setFirstName] = useState('First')\n  const [lastName, setLastName] = useState('Last')\n  const [fullName, setFullName] = useState('')\n\n  useEffect(() => {\n    setFullName(firstName + ' ' + lastName)\n  }, [firstName, lastName])\n\n  return <p>{fullName}</p>\n}",
    "language": "tsx",
    "description": "redundant state and effect"
  },
  {
    "ruleId": "",
    "ruleTitle": "Calculate Derived State During Rendering",
    "type": "good",
    "code": "function Form() {\n  const [firstName, setFirstName] = useState('First')\n  const [lastName, setLastName] = useState('Last')\n  const fullName = firstName + ' ' + lastName\n\n  return <p>{fullName}</p>\n}",
    "language": "tsx",
    "description": "derive during render"
  },
  {
    "ruleId": "",
    "ruleTitle": "Subscribe to Derived State",
    "type": "bad",
    "code": "function Sidebar() {\n  const width = useWindowWidth()  // updates continuously\n  const isMobile = width < 768\n  return <nav className={isMobile ? 'mobile' : 'desktop'} />\n}",
    "language": "tsx",
    "description": "re-renders on every pixel change"
  },
  {
    "ruleId": "",
    "ruleTitle": "Subscribe to Derived State",
    "type": "good",
    "code": "function Sidebar() {\n  const isMobile = useMediaQuery('(max-width: 767px)')\n  return <nav className={isMobile ? 'mobile' : 'desktop'} />\n}",
    "language": "tsx",
    "description": "re-renders only when boolean changes"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Functional setState Updates",
    "type": "bad",
    "code": "function TodoList() {\n  const [items, setItems] = useState(initialItems)\n  \n  // Callback must depend on items, recreated on every items change\n  const addItems = useCallback((newItems: Item[]) => {\n    setItems([...items, ...newItems])\n  }, [items])  // ❌ items dependency causes recreations\n  \n  // Risk of stale closure if dependency is forgotten\n  const removeItem = useCallback((id: string) => {\n    setItems(items.filter(item => item.id !== id))\n  }, [])  // ❌ Missing items dependency - will use stale items!\n  \n  return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />\n}",
    "language": "tsx",
    "description": "requires state as dependency"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Functional setState Updates",
    "type": "good",
    "code": "function TodoList() {\n  const [items, setItems] = useState(initialItems)\n  \n  // Stable callback, never recreated\n  const addItems = useCallback((newItems: Item[]) => {\n    setItems(curr => [...curr, ...newItems])\n  }, [])  // ✅ No dependencies needed\n  \n  // Always uses latest state, no stale closure risk\n  const removeItem = useCallback((id: string) => {\n    setItems(curr => curr.filter(item => item.id !== id))\n  }, [])  // ✅ Safe and stable\n  \n  return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />\n}",
    "language": "tsx",
    "description": "stable callbacks, no stale closures"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Lazy State Initialization",
    "type": "bad",
    "code": "function FilteredList({ items }: { items: Item[] }) {\n  // buildSearchIndex() runs on EVERY render, even after initialization\n  const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))\n  const [query, setQuery] = useState('')\n  \n  // When query changes, buildSearchIndex runs again unnecessarily\n  return <SearchResults index={searchIndex} query={query} />\n}\n\nfunction UserProfile() {\n  // JSON.parse runs on every render\n  const [settings, setSettings] = useState(\n    JSON.parse(localStorage.getItem('settings') || '{}')\n  )\n  \n  return <SettingsForm settings={settings} onChange={setSettings} />\n}",
    "language": "tsx",
    "description": "runs on every render"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Lazy State Initialization",
    "type": "good",
    "code": "function FilteredList({ items }: { items: Item[] }) {\n  // buildSearchIndex() runs ONLY on initial render\n  const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))\n  const [query, setQuery] = useState('')\n  \n  return <SearchResults index={searchIndex} query={query} />\n}\n\nfunction UserProfile() {\n  // JSON.parse runs only on initial render\n  const [settings, setSettings] = useState(() => {\n    const stored = localStorage.getItem('settings')\n    return stored ? JSON.parse(stored) : {}\n  })\n  \n  return <SettingsForm settings={settings} onChange={setSettings} />\n}",
    "language": "tsx",
    "description": "runs only once"
  },
  {
    "ruleId": "",
    "ruleTitle": "Extract Default Non-primitive Parameter Value from Memoized Component to Constant",
    "type": "bad",
    "code": "const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {\n  // ...\n})\n\n// Used without optional onClick\n<UserAvatar />",
    "language": "tsx",
    "description": "`onClick` has different values on every rerender"
  },
  {
    "ruleId": "",
    "ruleTitle": "Extract Default Non-primitive Parameter Value from Memoized Component to Constant",
    "type": "good",
    "code": "const NOOP = () => {};\n\nconst UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {\n  // ...\n})\n\n// Used without optional onClick\n<UserAvatar />",
    "language": "tsx",
    "description": "stable default value"
  },
  {
    "ruleId": "",
    "ruleTitle": "Extract to Memoized Components",
    "type": "bad",
    "code": "function Profile({ user, loading }: Props) {\n  const avatar = useMemo(() => {\n    const id = computeAvatarId(user)\n    return <Avatar id={id} />\n  }, [user])\n\n  if (loading) return <Skeleton />\n  return <div>{avatar}</div>\n}",
    "language": "tsx",
    "description": "computes avatar even when loading"
  },
  {
    "ruleId": "",
    "ruleTitle": "Extract to Memoized Components",
    "type": "good",
    "code": "const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {\n  const id = useMemo(() => computeAvatarId(user), [user])\n  return <Avatar id={id} />\n})\n\nfunction Profile({ user, loading }: Props) {\n  if (loading) return <Skeleton />\n  return (\n    <div>\n      <UserAvatar user={user} />\n    </div>\n  )\n}",
    "language": "tsx",
    "description": "skips computation when loading"
  },
  {
    "ruleId": "",
    "ruleTitle": "Put Interaction Logic in Event Handlers",
    "type": "bad",
    "code": "function Form() {\n  const [submitted, setSubmitted] = useState(false)\n  const theme = useContext(ThemeContext)\n\n  useEffect(() => {\n    if (submitted) {\n      post('/api/register')\n      showToast('Registered', theme)\n    }\n  }, [submitted, theme])\n\n  return <button onClick={() => setSubmitted(true)}>Submit</button>\n}",
    "language": "tsx",
    "description": "event modeled as state + effect"
  },
  {
    "ruleId": "",
    "ruleTitle": "Put Interaction Logic in Event Handlers",
    "type": "good",
    "code": "function Form() {\n  const theme = useContext(ThemeContext)\n\n  function handleSubmit() {\n    post('/api/register')\n    showToast('Registered', theme)\n  }\n\n  return <button onClick={handleSubmit}>Submit</button>\n}",
    "language": "tsx",
    "description": "do it in the handler"
  },
  {
    "ruleId": "",
    "ruleTitle": "Don't Define Components Inside Components",
    "type": "bad",
    "code": "function UserProfile({ user, theme }) {\n  // Defined inside to access `theme` - BAD\n  const Avatar = () => (\n    <img\n      src={user.avatarUrl}\n      className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}\n    />\n  )\n\n  // Defined inside to access `user` - BAD\n  const Stats = () => (\n    <div>\n      <span>{user.followers} followers</span>\n      <span>{user.posts} posts</span>\n    </div>\n  )\n\n  return (\n    <div>\n      <Avatar />\n      <Stats />\n    </div>\n  )\n}",
    "language": "tsx",
    "description": "remounts on every render"
  },
  {
    "ruleId": "",
    "ruleTitle": "Don't Define Components Inside Components",
    "type": "good",
    "code": "function Avatar({ src, theme }: { src: string; theme: string }) {\n  return (\n    <img\n      src={src}\n      className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}\n    />\n  )\n}\n\nfunction Stats({ followers, posts }: { followers: number; posts: number }) {\n  return (\n    <div>\n      <span>{followers} followers</span>\n      <span>{posts} posts</span>\n    </div>\n  )\n}\n\nfunction UserProfile({ user, theme }) {\n  return (\n    <div>\n      <Avatar src={user.avatarUrl} theme={theme} />\n      <Stats followers={user.followers} posts={user.posts} />\n    </div>\n  )\n}",
    "language": "tsx",
    "description": "pass props instead"
  },
  {
    "ruleId": "",
    "ruleTitle": "Do not wrap a simple expression with a primitive result type in useMemo",
    "type": "bad",
    "code": "function Header({ user, notifications }: Props) {\n  const isLoading = useMemo(() => {\n    return user.isLoading || notifications.isLoading\n  }, [user.isLoading, notifications.isLoading])\n\n  if (isLoading) return <Skeleton />\n  // return some markup\n}",
    "language": "tsx",
    "description": "Incorrect example for Do not wrap a simple expression with a primitive result type in useMemo"
  },
  {
    "ruleId": "",
    "ruleTitle": "Do not wrap a simple expression with a primitive result type in useMemo",
    "type": "good",
    "code": "function Header({ user, notifications }: Props) {\n  const isLoading = user.isLoading || notifications.isLoading\n\n  if (isLoading) return <Skeleton />\n  // return some markup\n}",
    "language": "tsx",
    "description": "Correct example for Do not wrap a simple expression with a primitive result type in useMemo"
  },
  {
    "ruleId": "",
    "ruleTitle": "Split Combined Hook Computations",
    "type": "bad",
    "code": "const sortedProducts = useMemo(() => {\n  const filtered = products.filter((p) => p.category === category)\n  const sorted = filtered.toSorted((a, b) =>\n    sortOrder === \"asc\" ? a.price - b.price : b.price - a.price\n  )\n  return sorted\n}, [products, category, sortOrder])",
    "language": "tsx",
    "description": "changing `sortOrder` recomputes filtering"
  },
  {
    "ruleId": "",
    "ruleTitle": "Split Combined Hook Computations",
    "type": "good",
    "code": "const filteredProducts = useMemo(\n  () => products.filter((p) => p.category === category),\n  [products, category]\n)\n\nconst sortedProducts = useMemo(\n  () =>\n    filteredProducts.toSorted((a, b) =>\n      sortOrder === \"asc\" ? a.price - b.price : b.price - a.price\n    ),\n  [filteredProducts, sortOrder]\n)",
    "language": "tsx",
    "description": "filtering only recomputes when products or category change"
  },
  {
    "ruleId": "",
    "ruleTitle": "Split Combined Hook Computations",
    "type": "bad",
    "code": "useEffect(() => {\n  analytics.trackPageView(pathname)\n  document.title = `${pageTitle} | My App`\n}, [pathname, pageTitle])",
    "language": "tsx",
    "description": "both effects run when either dependency changes"
  },
  {
    "ruleId": "",
    "ruleTitle": "Split Combined Hook Computations",
    "type": "good",
    "code": "useEffect(() => {\n  analytics.trackPageView(pathname)\n}, [pathname])\n\nuseEffect(() => {\n  document.title = `${pageTitle} | My App`\n}, [pageTitle])",
    "language": "tsx",
    "description": "effects run independently"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Transitions for Non-Urgent Updates",
    "type": "bad",
    "code": "function ScrollTracker() {\n  const [scrollY, setScrollY] = useState(0)\n  useEffect(() => {\n    const handler = () => setScrollY(window.scrollY)\n    window.addEventListener('scroll', handler, { passive: true })\n    return () => window.removeEventListener('scroll', handler)\n  }, [])\n}",
    "language": "tsx",
    "description": "blocks UI on every scroll"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use Transitions for Non-Urgent Updates",
    "type": "good",
    "code": "import { startTransition } from 'react'\n\nfunction ScrollTracker() {\n  const [scrollY, setScrollY] = useState(0)\n  useEffect(() => {\n    const handler = () => {\n      startTransition(() => setScrollY(window.scrollY))\n    }\n    window.addEventListener('scroll', handler, { passive: true })\n    return () => window.removeEventListener('scroll', handler)\n  }, [])\n}",
    "language": "tsx",
    "description": "non-blocking updates"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use useDeferredValue for Expensive Derived Renders",
    "type": "bad",
    "code": "function Search({ items }: { items: Item[] }) {\n  const [query, setQuery] = useState('')\n  const filtered = items.filter(item => fuzzyMatch(item, query))\n\n  return (\n    <>\n      <input value={query} onChange={e => setQuery(e.target.value)} />\n      <ResultsList results={filtered} />\n    </>\n  )\n}",
    "language": "tsx",
    "description": "input feels laggy while filtering"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use useDeferredValue for Expensive Derived Renders",
    "type": "good",
    "code": "function Search({ items }: { items: Item[] }) {\n  const [query, setQuery] = useState('')\n  const deferredQuery = useDeferredValue(query)\n  const filtered = useMemo(\n    () => items.filter(item => fuzzyMatch(item, deferredQuery)),\n    [items, deferredQuery]\n  )\n  const isStale = query !== deferredQuery\n\n  return (\n    <>\n      <input value={query} onChange={e => setQuery(e.target.value)} />\n      <div style={{ opacity: isStale ? 0.7 : 1 }}>\n        <ResultsList results={filtered} />\n      </div>\n    </>\n  )\n}",
    "language": "tsx",
    "description": "input stays snappy, results render when ready"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use useRef for Transient Values",
    "type": "bad",
    "code": "function Tracker() {\n  const [lastX, setLastX] = useState(0)\n\n  useEffect(() => {\n    const onMove = (e: MouseEvent) => setLastX(e.clientX)\n    window.addEventListener('mousemove', onMove)\n    return () => window.removeEventListener('mousemove', onMove)\n  }, [])\n\n  return (\n    <div\n      style={{\n        position: 'fixed',\n        top: 0,\n        left: lastX,\n        width: 8,\n        height: 8,\n        background: 'black',\n      }}\n    />\n  )\n}",
    "language": "tsx",
    "description": "renders every update"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use useRef for Transient Values",
    "type": "good",
    "code": "function Tracker() {\n  const lastXRef = useRef(0)\n  const dotRef = useRef<HTMLDivElement>(null)\n\n  useEffect(() => {\n    const onMove = (e: MouseEvent) => {\n      lastXRef.current = e.clientX\n      const node = dotRef.current\n      if (node) {\n        node.style.transform = `translateX(${e.clientX}px)`\n      }\n    }\n    window.addEventListener('mousemove', onMove)\n    return () => window.removeEventListener('mousemove', onMove)\n  }, [])\n\n  return (\n    <div\n      ref={dotRef}\n      style={{\n        position: 'fixed',\n        top: 0,\n        left: 0,\n        width: 8,\n        height: 8,\n        background: 'black',\n        transform: 'translateX(0px)',\n      }}\n    />\n  )\n}",
    "language": "tsx",
    "description": "no re-render for tracking"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use after() for Non-Blocking Operations",
    "type": "bad",
    "code": "import { logUserAction } from '@/app/utils'\n\nexport async function POST(request: Request) {\n  // Perform mutation\n  await updateDatabase(request)\n  \n  // Logging blocks the response\n  const userAgent = request.headers.get('user-agent') || 'unknown'\n  await logUserAction({ userAgent })\n  \n  return new Response(JSON.stringify({ status: 'success' }), {\n    status: 200,\n    headers: { 'Content-Type': 'application/json' }\n  })\n}",
    "language": "tsx",
    "description": "blocks response"
  },
  {
    "ruleId": "",
    "ruleTitle": "Use after() for Non-Blocking Operations",
    "type": "good",
    "code": "import { after } from 'next/server'\nimport { headers, cookies } from 'next/headers'\nimport { logUserAction } from '@/app/utils'\n\nexport async function POST(request: Request) {\n  // Perform mutation\n  await updateDatabase(request)\n  \n  // Log after response is sent\n  after(async () => {\n    const userAgent = (await headers()).get('user-agent') || 'unknown'\n    const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'\n    \n    logUserAction({ sessionCookie, userAgent })\n  })\n  \n  return new Response(JSON.stringify({ status: 'success' }), {\n    status: 200,\n    headers: { 'Content-Type': 'application/json' }\n  })\n}",
    "language": "tsx",
    "description": "non-blocking"
  },
  {
    "ruleId": "",
    "ruleTitle": "Authenticate Server Actions Like API Routes",
    "type": "bad",
    "code": "'use server'\n\nexport async function deleteUser(userId: string) {\n  // Anyone can call this! No auth check\n  await db.user.delete({ where: { id: userId } })\n  return { success: true }\n}",
    "language": "typescript",
    "description": "no authentication check"
  },
  {
    "ruleId": "",
    "ruleTitle": "Authenticate Server Actions Like API Routes",
    "type": "good",
    "code": "'use server'\n\nimport { verifySession } from '@/lib/auth'\nimport { unauthorized } from '@/lib/errors'\n\nexport async function deleteUser(userId: string) {\n  // Always check auth inside the action\n  const session = await verifySession()\n  \n  if (!session) {\n    throw unauthorized('Must be logged in')\n  }\n  \n  // Check authorization too\n  if (session.user.role !== 'admin' && session.user.id !== userId) {\n    throw unauthorized('Cannot delete other users')\n  }\n  \n  await db.user.delete({ where: { id: userId } })\n  return { success: true }\n}",
    "language": "typescript",
    "description": "authentication inside the action"
  },
  {
    "ruleId": "",
    "ruleTitle": "Per-Request Deduplication with React.cache()",
    "type": "bad",
    "code": "const getUser = cache(async (params: { uid: number }) => {\n  return await db.user.findUnique({ where: { id: params.uid } })\n})\n\n// Each call creates new object, never hits cache\ngetUser({ uid: 1 })\ngetUser({ uid: 1 })  // Cache miss, runs query again",
    "language": "typescript",
    "description": "always cache miss"
  },
  {
    "ruleId": "",
    "ruleTitle": "Per-Request Deduplication with React.cache()",
    "type": "good",
    "code": "const params = { uid: 1 }\ngetUser(params)  // Query runs\ngetUser(params)  // Cache hit (same reference)",
    "language": "typescript",
    "description": "cache hit"
  },
  {
    "ruleId": "",
    "ruleTitle": "Avoid Duplicate Serialization in RSC Props",
    "type": "bad",
    "code": "// RSC: sends 6 strings (2 arrays × 3 items)\n<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />",
    "language": "tsx",
    "description": "duplicates array"
  },
  {
    "ruleId": "",
    "ruleTitle": "Avoid Duplicate Serialization in RSC Props",
    "type": "good",
    "code": "// RSC: send once\n<ClientList usernames={usernames} />\n\n// Client: transform there\n'use client'\nconst sorted = useMemo(() => [...usernames].sort(), [usernames])",
    "language": "tsx",
    "description": "sends 3 strings"
  },
  {
    "ruleId": "",
    "ruleTitle": "Hoist Static I/O to Module Level",
    "type": "bad",
    "code": "// app/api/og/route.tsx\nimport { ImageResponse } from 'next/og'\n\nexport async function GET(request: Request) {\n  // Runs on EVERY request - expensive!\n  const fontData = await fetch(\n    new URL('./fonts/Inter.ttf', import.meta.url)\n  ).then(res => res.arrayBuffer())\n\n  const logoData = await fetch(\n    new URL('./images/logo.png', import.meta.url)\n  ).then(res => res.arrayBuffer())\n\n  return new ImageResponse(\n    <div style={{ fontFamily: 'Inter' }}>\n      <img src={logoData} />\n      Hello World\n    </div>,\n    { fonts: [{ name: 'Inter', data: fontData }] }\n  )\n}",
    "language": "typescript",
    "description": "reads font file on every request"
  },
  {
    "ruleId": "",
    "ruleTitle": "Hoist Static I/O to Module Level",
    "type": "good",
    "code": "// app/api/og/route.tsx\nimport { ImageResponse } from 'next/og'\n\n// Module-level: runs ONCE when module is first imported\nconst fontData = fetch(\n  new URL('./fonts/Inter.ttf', import.meta.url)\n).then(res => res.arrayBuffer())\n\nconst logoData = fetch(\n  new URL('./images/logo.png', import.meta.url)\n).then(res => res.arrayBuffer())\n\nexport async function GET(request: Request) {\n  // Await the already-started promises\n  const [font, logo] = await Promise.all([fontData, logoData])\n\n  return new ImageResponse(\n    <div style={{ fontFamily: 'Inter' }}>\n      <img src={logo} />\n      Hello World\n    </div>,\n    { fonts: [{ name: 'Inter', data: font }] }\n  )\n}",
    "language": "typescript",
    "description": "loads once at module initialization"
  },
  {
    "ruleId": "",
    "ruleTitle": "Hoist Static I/O to Module Level",
    "type": "good",
    "code": "// app/api/og/route.tsx\nimport { ImageResponse } from 'next/og'\nimport { readFileSync } from 'fs'\nimport { join } from 'path'\n\n// Synchronous read at module level - blocks only during module init\nconst fontData = readFileSync(\n  join(process.cwd(), 'public/fonts/Inter.ttf')\n)\n\nconst logoData = readFileSync(\n  join(process.cwd(), 'public/images/logo.png')\n)\n\nexport async function GET(request: Request) {\n  return new ImageResponse(\n    <div style={{ fontFamily: 'Inter' }}>\n      <img src={logoData} />\n      Hello World\n    </div>,\n    { fonts: [{ name: 'Inter', data: fontData }] }\n  )\n}",
    "language": "typescript",
    "description": "synchronous fs at module level"
  },
  {
    "ruleId": "",
    "ruleTitle": "Hoist Static I/O to Module Level",
    "type": "bad",
    "code": "import fs from 'node:fs/promises'\n\nexport async function processRequest(data: Data) {\n  const config = JSON.parse(\n    await fs.readFile('./config.json', 'utf-8')\n  )\n  const template = await fs.readFile('./template.html', 'utf-8')\n\n  return render(template, data, config)\n}",
    "language": "typescript",
    "description": "reads config on every call"
  },
  {
    "ruleId": "",
    "ruleTitle": "Hoist Static I/O to Module Level",
    "type": "good",
    "code": "import fs from 'node:fs/promises'\n\nconst configPromise = fs\n  .readFile('./config.json', 'utf-8')\n  .then(JSON.parse)\nconst templatePromise = fs.readFile('./template.html', 'utf-8')\n\nexport async function processRequest(data: Data) {\n  const [config, template] = await Promise.all([\n    configPromise,\n    templatePromise,\n  ])\n\n  return render(template, data, config)\n}",
    "language": "typescript",
    "description": "hoists config and template to module level"
  },
  {
    "ruleId": "",
    "ruleTitle": "Avoid Shared Module State for Request Data",
    "type": "bad",
    "code": "let currentUser: User | null = null\n\nexport default async function Page() {\n  currentUser = await auth()\n  return <Dashboard />\n}\n\nasync function Dashboard() {\n  return <div>{currentUser?.name}</div>\n}",
    "language": "tsx",
    "description": "request data leaks across concurrent renders"
  },
  {
    "ruleId": "",
    "ruleTitle": "Avoid Shared Module State for Request Data",
    "type": "good",
    "code": "export default async function Page() {\n  const user = await auth()\n  return <Dashboard user={user} />\n}\n\nfunction Dashboard({ user }: { user: User | null }) {\n  return <div>{user?.name}</div>\n}",
    "language": "tsx",
    "description": "keep request data local to the render tree"
  },
  {
    "ruleId": "",
    "ruleTitle": "Parallel Data Fetching with Component Composition",
    "type": "bad",
    "code": "export default async function Page() {\n  const header = await fetchHeader()\n  return (\n    <div>\n      <div>{header}</div>\n      <Sidebar />\n    </div>\n  )\n}\n\nasync function Sidebar() {\n  const items = await fetchSidebarItems()\n  return <nav>{items.map(renderItem)}</nav>\n}",
    "language": "tsx",
    "description": "Sidebar waits for Page's fetch to complete"
  },
  {
    "ruleId": "",
    "ruleTitle": "Parallel Data Fetching with Component Composition",
    "type": "good",
    "code": "async function Header() {\n  const data = await fetchHeader()\n  return <div>{data}</div>\n}\n\nasync function Sidebar() {\n  const items = await fetchSidebarItems()\n  return <nav>{items.map(renderItem)}</nav>\n}\n\nexport default function Page() {\n  return (\n    <div>\n      <Header />\n      <Sidebar />\n    </div>\n  )\n}",
    "language": "tsx",
    "description": "both fetch simultaneously"
  },
  {
    "ruleId": "",
    "ruleTitle": "Parallel Nested Data Fetching",
    "type": "bad",
    "code": "const chats = await Promise.all(\n  chatIds.map(id => getChat(id))\n)\n\nconst chatAuthors = await Promise.all(\n  chats.map(chat => getUser(chat.author))\n)",
    "language": "tsx",
    "description": "a single slow item blocks all nested fetches"
  },
  {
    "ruleId": "",
    "ruleTitle": "Parallel Nested Data Fetching",
    "type": "good",
    "code": "const chatAuthors = await Promise.all(\n  chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))\n)",
    "language": "tsx",
    "description": "each item chains its own nested fetch"
  },
  {
    "ruleId": "",
    "ruleTitle": "Minimize Serialization at RSC Boundaries",
    "type": "bad",
    "code": "async function Page() {\n  const user = await fetchUser()  // 50 fields\n  return <Profile user={user} />\n}\n\n'use client'\nfunction Profile({ user }: { user: User }) {\n  return <div>{user.name}</div>  // uses 1 field\n}",
    "language": "tsx",
    "description": "serializes all 50 fields"
  },
  {
    "ruleId": "",
    "ruleTitle": "Minimize Serialization at RSC Boundaries",
    "type": "good",
    "code": "async function Page() {\n  const user = await fetchUser()\n  return <Profile name={user.name} />\n}\n\n'use client'\nfunction Profile({ name }: { name: string }) {\n  return <div>{name}</div>\n}",
    "language": "tsx",
    "description": "serializes only 1 field"
  }
]