From 44f4fa98e23365a4acb86885caecc1944c2ccfd8 Mon Sep 17 00:00:00 2001 From: Darian Date: Thu, 24 Sep 2026 14:53:01 +0330 Subject: [PATCH] Enhance Next.js configuration and dependencies for improved functionality and localization support. Added support for internationalization with next-intl, updated global styles, and integrated new fonts. Removed default home page and updated README with project details and setup instructions. --- .agents/skills/design-system-rules/SKILL.md | 28 + .agents/skills/material-design/SKILL.md | 165 + .agents/skills/shadcn-ui/SKILL.md | 33 + .../vercel-react-best-practices/AGENTS.md | 3810 +++++++++++++++ .../vercel-react-best-practices/README.md | 123 + .../vercel-react-best-practices/SKILL.md | 149 + .../rules/_sections.md | 46 + .../rules/_template.md | 28 + .../rules/advanced-effect-event-deps.md | 56 + .../rules/advanced-event-handler-refs.md | 55 + .../rules/advanced-init-once.md | 42 + .../rules/advanced-use-latest.md | 39 + .../rules/async-api-routes.md | 38 + .../async-cheap-condition-before-await.md | 37 + .../rules/async-defer-await.md | 82 + .../rules/async-dependencies.md | 51 + .../rules/async-parallel.md | 28 + .../rules/async-suspense-boundaries.md | 99 + .../rules/bundle-analyzable-paths.md | 63 + .../rules/bundle-barrel-imports.md | 60 + .../rules/bundle-conditional.md | 31 + .../rules/bundle-defer-third-party.md | 49 + .../rules/bundle-dynamic-imports.md | 35 + .../rules/bundle-preload.md | 50 + .../rules/client-event-listeners.md | 74 + .../rules/client-localstorage-schema.md | 71 + .../rules/client-passive-event-listeners.md | 48 + .../rules/client-swr-dedup.md | 56 + .../rules/js-batch-dom-css.md | 107 + .../rules/js-cache-function-results.md | 80 + .../rules/js-cache-property-access.md | 28 + .../rules/js-cache-storage.md | 70 + .../rules/js-combine-iterations.md | 32 + .../rules/js-early-exit.md | 50 + .../rules/js-flatmap-filter.md | 60 + .../rules/js-hoist-regexp.md | 45 + .../rules/js-index-maps.md | 37 + .../rules/js-length-check-first.md | 49 + .../rules/js-min-max-loop.md | 82 + .../rules/js-request-idle-callback.md | 105 + .../rules/js-set-map-lookups.md | 24 + .../rules/js-tosorted-immutable.md | 57 + .../rules/rendering-activity.md | 26 + .../rules/rendering-animate-svg-wrapper.md | 47 + .../rules/rendering-conditional-render.md | 40 + .../rules/rendering-content-visibility.md | 38 + .../rules/rendering-hoist-jsx.md | 46 + .../rules/rendering-hydration-no-flicker.md | 82 + .../rendering-hydration-suppress-warning.md | 30 + .../rules/rendering-resource-hints.md | 85 + .../rules/rendering-script-defer-async.md | 68 + .../rules/rendering-svg-precision.md | 28 + .../rules/rendering-usetransition-loading.md | 75 + .../rules/rerender-defer-reads.md | 39 + .../rules/rerender-dependencies.md | 45 + .../rules/rerender-derived-state-no-effect.md | 40 + .../rules/rerender-derived-state.md | 29 + .../rules/rerender-functional-setstate.md | 74 + .../rules/rerender-lazy-state-init.md | 58 + .../rules/rerender-memo-with-default-value.md | 38 + .../rules/rerender-memo.md | 44 + .../rules/rerender-move-effect-to-event.md | 45 + .../rules/rerender-no-inline-components.md | 82 + .../rerender-simple-expression-in-memo.md | 35 + .../rules/rerender-split-combined-hooks.md | 64 + .../rules/rerender-transitions.md | 40 + .../rules/rerender-use-deferred-value.md | 59 + .../rerender-use-ref-transient-values.md | 73 + .../rules/server-after-nonblocking.md | 73 + .../rules/server-auth-actions.md | 96 + .../rules/server-cache-lru.md | 41 + .../rules/server-cache-react.md | 76 + .../rules/server-dedup-props.md | 65 + .../rules/server-hoist-static-io.md | 149 + .../rules/server-no-shared-module-state.md | 50 + .../rules/server-parallel-fetching.md | 83 + .../rules/server-parallel-nested-fetching.md | 34 + .../rules/server-serialization.md | 38 + .claude/skills/design-system-rules/SKILL.md | 28 + .claude/skills/frontend-excellence/SKILL.md | 175 + .claude/skills/material-design/SKILL.md | 165 + .claude/skills/mobile-development/SKILL.md | 219 + .claude/skills/nextjs-mastery/SKILL.md | 161 + .claude/skills/shadcn-ui/SKILL.md | 33 + .cursor/rules/design-bootstrap.mdc | 15 + .cursor/rules/ui-architecture.mdc | 28 + .dockerignore | 59 + .github/architect.chatmode.md | 177 + .github/ask.chatmode.md | 122 + .github/code.chatmode.md | 157 + .github/debug.chatmode.md | 158 + .github/workflows/deploy.yml | 62 + .vscode/settings.json | 1 + Dockerfile | 36 + PLAYBOOK.md | 78 + PROJECT-INIT.md | 27 + README.md | 78 +- components.json | 25 + db/migrate.mjs | 92 + db/migrations/001_init.sql | 215 + db/migrations/002_indexes.sql | 23 + db/migrations/003_course_price.sql | 4 + db/seed.mjs | 146 + docker-compose.yml | 25 + docs/00-brief.md | 36 + docs/01-architecture.md | 109 + docs/02-domain-rules.md | 67 + docs/03-database.md | 101 + docs/04-development-plan.md | 546 +++ docs/DESIGN_SYSTEM_AUDIT.md | 121 + docs/design-system-rules.md | 56 + docs/log/ambiguities.md | 21 + docs/log/decisions.md | 29 + docs/reference/mitsloan/00-index.md | 117 + docs/reference/mitsloan/01-homepage.md | 93 + docs/reference/mitsloan/02-programs.md | 179 + .../mitsloan/03-ideas-made-to-matter.md | 39 + docs/reference/mitsloan/04-events.md | 32 + docs/reference/mitsloan/05-alumni.md | 15 + docs/reference/mitsloan/06-faculty.md | 23 + docs/reference/mitsloan/07-values.md | 15 + docs/reference/mitsloan/08-about.md | 35 + .../mitsloan/09-executive-education.md | 35 + docs/reference/mitsloan/10-intersections.md | 66 + docs/reference/mitsloan/11-utility-footer.md | 61 + docs/reference/mitsloan/12-design-system.md | 61 + docs/state/active-context.md | 23 + docs/state/progress.md | 54 + memory-bank/activeContext.md | 9 + memory-bank/architect.md | 11 + memory-bank/decisionLog.md | 4 + memory-bank/productContext.md | 17 + memory-bank/progress.md | 13 + memory-bank/projectBrief.md | 9 + memory-bank/systemPatterns.md | 13 + messages/fa.json | 97 + mit-sites-reconstruction-spec.md | 259 ++ next.config.ts | 18 +- package-lock.json | 4087 ++++++++++++++++- package.json | 13 +- public/brand/amirkabir.png | Bin 0 -> 40797 bytes public/brand/campus-collaboration-v1.png | Bin 0 -> 1967843 bytes run-mvp.bat | 29 + scripts/seed-admin.mjs | 56 + scripts/smoke.mjs | 92 + scripts/test-db-connection.mjs | 42 + skills-lock.json | 11 + skills/expert-next-js-developer/SKILL.md | 475 ++ src/app/(main)/(legal)/[slug]/page.tsx | 43 + src/app/(main)/about/page.tsx | 67 + src/app/(main)/alumni/page.tsx | 60 + src/app/(main)/contact/page.tsx | 74 + src/app/(main)/error.tsx | 35 + src/app/(main)/events/[id]/page.tsx | 58 + src/app/(main)/events/page.tsx | 32 + src/app/(main)/faculty/page.tsx | 54 + src/app/(main)/insights/[id]/page.tsx | 74 + src/app/(main)/insights/page.tsx | 40 + src/app/(main)/layout.tsx | 52 + src/app/(main)/page.tsx | 98 + src/app/(main)/programs/[slug]/page.tsx | 108 + src/app/(main)/programs/page.tsx | 90 + src/app/(main)/register/[slug]/page.tsx | 49 + src/app/(main)/topics/[slug]/page.tsx | 60 + src/app/(main)/values/page.tsx | 40 + .../admin/(guard)/[entity]/[id]/edit/page.tsx | 43 + src/app/admin/(guard)/[entity]/new/page.tsx | 43 + src/app/admin/(guard)/[entity]/page.tsx | 61 + .../admin/(guard)/courses/[id]/edit/page.tsx | 31 + src/app/admin/(guard)/courses/new/page.tsx | 21 + src/app/admin/(guard)/courses/page.tsx | 54 + src/app/admin/(guard)/layout.tsx | 21 + src/app/admin/(guard)/page.tsx | 120 + src/app/admin/(guard)/registrations/page.tsx | 46 + src/app/admin/login/page.tsx | 132 + src/app/api/admin/alumni/[id]/route.ts | 79 + src/app/api/admin/alumni/route.ts | 47 + src/app/api/admin/articles/[id]/route.ts | 100 + src/app/api/admin/articles/route.ts | 56 + src/app/api/admin/banners/[id]/route.ts | 77 + src/app/api/admin/banners/route.ts | 47 + src/app/api/admin/courses/[id]/route.ts | 118 + src/app/api/admin/courses/route.ts | 80 + src/app/api/admin/events/[id]/route.ts | 76 + src/app/api/admin/events/route.ts | 47 + src/app/api/admin/faculty/[id]/route.ts | 78 + src/app/api/admin/faculty/route.ts | 47 + src/app/api/admin/legal/[slug]/route.ts | 80 + src/app/api/admin/legal/route.ts | 50 + src/app/api/admin/login/route.ts | 34 + src/app/api/admin/logout/route.ts | 13 + src/app/api/admin/programs/[id]/route.ts | 90 + src/app/api/admin/programs/route.ts | 51 + src/app/api/admin/registrations/[id]/route.ts | 66 + src/app/api/admin/registrations/route.ts | 38 + src/app/api/admin/stats/[id]/route.ts | 72 + src/app/api/admin/stats/route.ts | 47 + src/app/api/admin/testimonials/[id]/route.ts | 77 + src/app/api/admin/testimonials/route.ts | 47 + src/app/api/admin/topics/[id]/route.ts | 89 + src/app/api/admin/topics/route.ts | 51 + src/app/api/articles/[id]/route.ts | 13 + src/app/api/articles/route.ts | 7 + src/app/api/courses/[id]/route.ts | 13 + src/app/api/courses/route.ts | 7 + src/app/api/events/[id]/route.ts | 13 + src/app/api/events/route.ts | 7 + src/app/api/programs/[slug]/route.ts | 13 + src/app/api/programs/route.ts | 7 + src/app/api/registrations/route.ts | 52 + src/app/apple-icon.png | Bin 0 -> 40797 bytes src/app/globals.css | 299 +- src/app/icon.png | Bin 0 -> 40797 bytes src/app/layout.tsx | 116 +- src/app/page.tsx | 69 - src/app/professional/error.tsx | 40 + src/app/professional/layout.tsx | 47 + src/app/professional/page.tsx | 56 + src/components/atoms/AnimatedMetric.tsx | 39 + src/components/atoms/BadgeLabel.tsx | 27 + src/components/atoms/BrandLogo.tsx | 73 + src/components/atoms/Container.tsx | 22 + src/components/atoms/DotCta.tsx | 50 + src/components/atoms/Heading.tsx | 18 + src/components/atoms/MetamorphField.tsx | 221 + src/components/atoms/MorphMark.tsx | 37 + src/components/atoms/Section.tsx | 33 + src/components/atoms/TextLink.tsx | 25 + src/components/molecules/Cards.tsx | 288 ++ src/components/molecules/HeroFeatured.tsx | 56 + src/components/molecules/PageHero.tsx | 23 + src/components/molecules/SurfaceCard.tsx | 41 + src/components/organisms/AcademicsOverlay.tsx | 108 + src/components/organisms/CampaignBanners.tsx | 74 + .../organisms/CategoryCourseExplorer.tsx | 152 + .../organisms/ContactInterestForm.tsx | 108 + .../organisms/CourseRegisterGate.tsx | 79 + src/components/organisms/ProgramCarousel.tsx | 79 + src/components/organisms/SearchOverlay.tsx | 171 + src/components/organisms/SiteFooter.tsx | 95 + src/components/organisms/SiteHeader.tsx | 211 + src/components/organisms/admin/AdminPage.tsx | 134 + src/components/organisms/admin/AdminShell.tsx | 63 + .../organisms/admin/AdminSidebar.tsx | 173 + src/components/organisms/admin/LeadsList.tsx | 108 + .../organisms/admin/LogoutButton.tsx | 28 + .../organisms/admin/courses/CourseFilters.tsx | 85 + .../organisms/admin/courses/CourseForm.tsx | 298 ++ .../organisms/admin/courses/CourseTable.tsx | 86 + .../admin/courses/DeleteCourseDialog.tsx | 63 + .../organisms/admin/courses/PublishToggle.tsx | 46 + .../admin/generic/GenericDeleteDialog.tsx | 73 + .../admin/generic/GenericFilters.tsx | 90 + .../organisms/admin/generic/GenericForm.tsx | 268 ++ .../organisms/admin/generic/GenericTable.tsx | 101 + .../organisms/admin/generic/PublishToggle.tsx | 54 + .../registrations/RegistrationFilters.tsx | 84 + .../registrations/RegistrationsTable.tsx | 163 + .../templates/CourseDetailTemplate.tsx | 179 + src/components/templates/HomeTemplate.tsx | 281 ++ .../templates/ProfessionalLandingTemplate.tsx | 173 + src/components/ui/accordion.tsx | 71 + src/components/ui/avatar.tsx | 108 + src/components/ui/badge.tsx | 51 + src/components/ui/breadcrumb.tsx | 124 + src/components/ui/button.tsx | 65 + src/components/ui/card.tsx | 102 + src/components/ui/dialog.tsx | 160 + src/components/ui/dropdown-menu.tsx | 267 ++ src/components/ui/input.tsx | 19 + src/components/ui/label.tsx | 19 + src/components/ui/navigation-menu.tsx | 167 + src/components/ui/scroll-area.tsx | 54 + src/components/ui/select.tsx | 200 + src/components/ui/separator.tsx | 24 + src/components/ui/sheet.tsx | 138 + src/components/ui/sidebar.tsx | 723 +++ src/components/ui/skeleton.tsx | 13 + src/components/ui/table.tsx | 115 + src/components/ui/tabs.tsx | 81 + src/components/ui/textarea.tsx | 17 + src/components/ui/tooltip.tsx | 65 + src/fonts/iransans/IRANSans.woff2 | Bin 0 -> 30852 bytes src/fonts/iransans/IRANSansBold.woff2 | Bin 0 -> 29244 bytes src/fonts/iransans/IRANSansLight.woff2 | Bin 0 -> 32144 bytes src/fonts/iransans/IRANSansMedium.woff2 | Bin 0 -> 28676 bytes src/fonts/iransans/IRANSansUltraLight.woff2 | Bin 0 -> 29632 bytes src/hooks/use-mobile.ts | 19 + src/i18n/request.ts | 9 + src/lib/admin/entities.ts | 399 ++ src/lib/api/crud.ts | 67 + src/lib/api/response.ts | 7 + src/lib/api/revalidate.ts | 9 + src/lib/auth/admin.ts | 108 + src/lib/data/admin/cms.ts | 165 + src/lib/data/admin/courses.ts | 33 + src/lib/data/admin/helpers.ts | 54 + src/lib/data/admin/registrations.ts | 46 + src/lib/data/articles.ts | 25 + src/lib/data/courses.ts | 18 + src/lib/data/events.ts | 18 + src/lib/data/programs.ts | 28 + src/lib/data/site.ts | 86 + src/lib/db.ts | 23 + src/lib/db/errors.ts | 15 + src/lib/db/mappers.ts | 440 ++ src/lib/images.ts | 3 + src/lib/labels.ts | 31 + src/lib/mock/articles.ts | 57 + src/lib/mock/courses.ts | 89 + src/lib/mock/events.ts | 44 + src/lib/mock/programs.ts | 165 + src/lib/mock/site.ts | 352 ++ src/lib/seo/json-ld.tsx | 53 + src/lib/site-config.ts | 102 + src/lib/types/index.ts | 128 + src/lib/utils.ts | 1 + src/lib/validation/admin.ts | 260 ++ src/lib/validation/public.ts | 11 + src/proxy.ts | 31 + 320 files changed, 31666 insertions(+), 220 deletions(-) create mode 100644 .agents/skills/design-system-rules/SKILL.md create mode 100644 .agents/skills/material-design/SKILL.md create mode 100644 .agents/skills/shadcn-ui/SKILL.md create mode 100644 .agents/skills/vercel-react-best-practices/AGENTS.md create mode 100644 .agents/skills/vercel-react-best-practices/README.md create mode 100644 .agents/skills/vercel-react-best-practices/SKILL.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/_sections.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/_template.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/advanced-init-once.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/async-api-routes.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/async-defer-await.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/async-dependencies.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/async-parallel.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/bundle-conditional.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/bundle-preload.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/client-event-listeners.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/js-cache-storage.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/js-early-exit.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/js-index-maps.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/js-length-check-first.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/js-request-idle-callback.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rendering-activity.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-dependencies.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-derived-state.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-memo.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-no-inline-components.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-transitions.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/server-auth-actions.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/server-cache-lru.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/server-cache-react.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/server-dedup-props.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/server-hoist-static-io.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/server-no-shared-module-state.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.md create mode 100644 .agents/skills/vercel-react-best-practices/rules/server-serialization.md create mode 100644 .claude/skills/design-system-rules/SKILL.md create mode 100644 .claude/skills/frontend-excellence/SKILL.md create mode 100644 .claude/skills/material-design/SKILL.md create mode 100644 .claude/skills/mobile-development/SKILL.md create mode 100644 .claude/skills/nextjs-mastery/SKILL.md create mode 100644 .claude/skills/shadcn-ui/SKILL.md create mode 100644 .cursor/rules/design-bootstrap.mdc create mode 100644 .cursor/rules/ui-architecture.mdc create mode 100644 .dockerignore create mode 100644 .github/architect.chatmode.md create mode 100644 .github/ask.chatmode.md create mode 100644 .github/code.chatmode.md create mode 100644 .github/debug.chatmode.md create mode 100644 .github/workflows/deploy.yml create mode 100644 .vscode/settings.json create mode 100644 Dockerfile create mode 100644 PLAYBOOK.md create mode 100644 PROJECT-INIT.md create mode 100644 components.json create mode 100644 db/migrate.mjs create mode 100644 db/migrations/001_init.sql create mode 100644 db/migrations/002_indexes.sql create mode 100644 db/migrations/003_course_price.sql create mode 100644 db/seed.mjs create mode 100644 docker-compose.yml create mode 100644 docs/00-brief.md create mode 100644 docs/01-architecture.md create mode 100644 docs/02-domain-rules.md create mode 100644 docs/03-database.md create mode 100644 docs/04-development-plan.md create mode 100644 docs/DESIGN_SYSTEM_AUDIT.md create mode 100644 docs/design-system-rules.md create mode 100644 docs/log/ambiguities.md create mode 100644 docs/log/decisions.md create mode 100644 docs/reference/mitsloan/00-index.md create mode 100644 docs/reference/mitsloan/01-homepage.md create mode 100644 docs/reference/mitsloan/02-programs.md create mode 100644 docs/reference/mitsloan/03-ideas-made-to-matter.md create mode 100644 docs/reference/mitsloan/04-events.md create mode 100644 docs/reference/mitsloan/05-alumni.md create mode 100644 docs/reference/mitsloan/06-faculty.md create mode 100644 docs/reference/mitsloan/07-values.md create mode 100644 docs/reference/mitsloan/08-about.md create mode 100644 docs/reference/mitsloan/09-executive-education.md create mode 100644 docs/reference/mitsloan/10-intersections.md create mode 100644 docs/reference/mitsloan/11-utility-footer.md create mode 100644 docs/reference/mitsloan/12-design-system.md create mode 100644 docs/state/active-context.md create mode 100644 docs/state/progress.md create mode 100644 memory-bank/activeContext.md create mode 100644 memory-bank/architect.md create mode 100644 memory-bank/decisionLog.md create mode 100644 memory-bank/productContext.md create mode 100644 memory-bank/progress.md create mode 100644 memory-bank/projectBrief.md create mode 100644 memory-bank/systemPatterns.md create mode 100644 messages/fa.json create mode 100644 mit-sites-reconstruction-spec.md create mode 100644 public/brand/amirkabir.png create mode 100644 public/brand/campus-collaboration-v1.png create mode 100644 run-mvp.bat create mode 100644 scripts/seed-admin.mjs create mode 100644 scripts/smoke.mjs create mode 100644 scripts/test-db-connection.mjs create mode 100644 skills-lock.json create mode 100644 skills/expert-next-js-developer/SKILL.md create mode 100644 src/app/(main)/(legal)/[slug]/page.tsx create mode 100644 src/app/(main)/about/page.tsx create mode 100644 src/app/(main)/alumni/page.tsx create mode 100644 src/app/(main)/contact/page.tsx create mode 100644 src/app/(main)/error.tsx create mode 100644 src/app/(main)/events/[id]/page.tsx create mode 100644 src/app/(main)/events/page.tsx create mode 100644 src/app/(main)/faculty/page.tsx create mode 100644 src/app/(main)/insights/[id]/page.tsx create mode 100644 src/app/(main)/insights/page.tsx create mode 100644 src/app/(main)/layout.tsx create mode 100644 src/app/(main)/page.tsx create mode 100644 src/app/(main)/programs/[slug]/page.tsx create mode 100644 src/app/(main)/programs/page.tsx create mode 100644 src/app/(main)/register/[slug]/page.tsx create mode 100644 src/app/(main)/topics/[slug]/page.tsx create mode 100644 src/app/(main)/values/page.tsx create mode 100644 src/app/admin/(guard)/[entity]/[id]/edit/page.tsx create mode 100644 src/app/admin/(guard)/[entity]/new/page.tsx create mode 100644 src/app/admin/(guard)/[entity]/page.tsx create mode 100644 src/app/admin/(guard)/courses/[id]/edit/page.tsx create mode 100644 src/app/admin/(guard)/courses/new/page.tsx create mode 100644 src/app/admin/(guard)/courses/page.tsx create mode 100644 src/app/admin/(guard)/layout.tsx create mode 100644 src/app/admin/(guard)/page.tsx create mode 100644 src/app/admin/(guard)/registrations/page.tsx create mode 100644 src/app/admin/login/page.tsx create mode 100644 src/app/api/admin/alumni/[id]/route.ts create mode 100644 src/app/api/admin/alumni/route.ts create mode 100644 src/app/api/admin/articles/[id]/route.ts create mode 100644 src/app/api/admin/articles/route.ts create mode 100644 src/app/api/admin/banners/[id]/route.ts create mode 100644 src/app/api/admin/banners/route.ts create mode 100644 src/app/api/admin/courses/[id]/route.ts create mode 100644 src/app/api/admin/courses/route.ts create mode 100644 src/app/api/admin/events/[id]/route.ts create mode 100644 src/app/api/admin/events/route.ts create mode 100644 src/app/api/admin/faculty/[id]/route.ts create mode 100644 src/app/api/admin/faculty/route.ts create mode 100644 src/app/api/admin/legal/[slug]/route.ts create mode 100644 src/app/api/admin/legal/route.ts create mode 100644 src/app/api/admin/login/route.ts create mode 100644 src/app/api/admin/logout/route.ts create mode 100644 src/app/api/admin/programs/[id]/route.ts create mode 100644 src/app/api/admin/programs/route.ts create mode 100644 src/app/api/admin/registrations/[id]/route.ts create mode 100644 src/app/api/admin/registrations/route.ts create mode 100644 src/app/api/admin/stats/[id]/route.ts create mode 100644 src/app/api/admin/stats/route.ts create mode 100644 src/app/api/admin/testimonials/[id]/route.ts create mode 100644 src/app/api/admin/testimonials/route.ts create mode 100644 src/app/api/admin/topics/[id]/route.ts create mode 100644 src/app/api/admin/topics/route.ts create mode 100644 src/app/api/articles/[id]/route.ts create mode 100644 src/app/api/articles/route.ts create mode 100644 src/app/api/courses/[id]/route.ts create mode 100644 src/app/api/courses/route.ts create mode 100644 src/app/api/events/[id]/route.ts create mode 100644 src/app/api/events/route.ts create mode 100644 src/app/api/programs/[slug]/route.ts create mode 100644 src/app/api/programs/route.ts create mode 100644 src/app/api/registrations/route.ts create mode 100644 src/app/apple-icon.png create mode 100644 src/app/icon.png delete mode 100644 src/app/page.tsx create mode 100644 src/app/professional/error.tsx create mode 100644 src/app/professional/layout.tsx create mode 100644 src/app/professional/page.tsx create mode 100644 src/components/atoms/AnimatedMetric.tsx create mode 100644 src/components/atoms/BadgeLabel.tsx create mode 100644 src/components/atoms/BrandLogo.tsx create mode 100644 src/components/atoms/Container.tsx create mode 100644 src/components/atoms/DotCta.tsx create mode 100644 src/components/atoms/Heading.tsx create mode 100644 src/components/atoms/MetamorphField.tsx create mode 100644 src/components/atoms/MorphMark.tsx create mode 100644 src/components/atoms/Section.tsx create mode 100644 src/components/atoms/TextLink.tsx create mode 100644 src/components/molecules/Cards.tsx create mode 100644 src/components/molecules/HeroFeatured.tsx create mode 100644 src/components/molecules/PageHero.tsx create mode 100644 src/components/molecules/SurfaceCard.tsx create mode 100644 src/components/organisms/AcademicsOverlay.tsx create mode 100644 src/components/organisms/CampaignBanners.tsx create mode 100644 src/components/organisms/CategoryCourseExplorer.tsx create mode 100644 src/components/organisms/ContactInterestForm.tsx create mode 100644 src/components/organisms/CourseRegisterGate.tsx create mode 100644 src/components/organisms/ProgramCarousel.tsx create mode 100644 src/components/organisms/SearchOverlay.tsx create mode 100644 src/components/organisms/SiteFooter.tsx create mode 100644 src/components/organisms/SiteHeader.tsx create mode 100644 src/components/organisms/admin/AdminPage.tsx create mode 100644 src/components/organisms/admin/AdminShell.tsx create mode 100644 src/components/organisms/admin/AdminSidebar.tsx create mode 100644 src/components/organisms/admin/LeadsList.tsx create mode 100644 src/components/organisms/admin/LogoutButton.tsx create mode 100644 src/components/organisms/admin/courses/CourseFilters.tsx create mode 100644 src/components/organisms/admin/courses/CourseForm.tsx create mode 100644 src/components/organisms/admin/courses/CourseTable.tsx create mode 100644 src/components/organisms/admin/courses/DeleteCourseDialog.tsx create mode 100644 src/components/organisms/admin/courses/PublishToggle.tsx create mode 100644 src/components/organisms/admin/generic/GenericDeleteDialog.tsx create mode 100644 src/components/organisms/admin/generic/GenericFilters.tsx create mode 100644 src/components/organisms/admin/generic/GenericForm.tsx create mode 100644 src/components/organisms/admin/generic/GenericTable.tsx create mode 100644 src/components/organisms/admin/generic/PublishToggle.tsx create mode 100644 src/components/organisms/admin/registrations/RegistrationFilters.tsx create mode 100644 src/components/organisms/admin/registrations/RegistrationsTable.tsx create mode 100644 src/components/templates/CourseDetailTemplate.tsx create mode 100644 src/components/templates/HomeTemplate.tsx create mode 100644 src/components/templates/ProfessionalLandingTemplate.tsx create mode 100644 src/components/ui/accordion.tsx create mode 100644 src/components/ui/avatar.tsx create mode 100644 src/components/ui/badge.tsx create mode 100644 src/components/ui/breadcrumb.tsx create mode 100644 src/components/ui/button.tsx create mode 100644 src/components/ui/card.tsx create mode 100644 src/components/ui/dialog.tsx create mode 100644 src/components/ui/dropdown-menu.tsx create mode 100644 src/components/ui/input.tsx create mode 100644 src/components/ui/label.tsx create mode 100644 src/components/ui/navigation-menu.tsx create mode 100644 src/components/ui/scroll-area.tsx create mode 100644 src/components/ui/select.tsx create mode 100644 src/components/ui/separator.tsx create mode 100644 src/components/ui/sheet.tsx create mode 100644 src/components/ui/sidebar.tsx create mode 100644 src/components/ui/skeleton.tsx create mode 100644 src/components/ui/table.tsx create mode 100644 src/components/ui/tabs.tsx create mode 100644 src/components/ui/textarea.tsx create mode 100644 src/components/ui/tooltip.tsx create mode 100644 src/fonts/iransans/IRANSans.woff2 create mode 100644 src/fonts/iransans/IRANSansBold.woff2 create mode 100644 src/fonts/iransans/IRANSansLight.woff2 create mode 100644 src/fonts/iransans/IRANSansMedium.woff2 create mode 100644 src/fonts/iransans/IRANSansUltraLight.woff2 create mode 100644 src/hooks/use-mobile.ts create mode 100644 src/i18n/request.ts create mode 100644 src/lib/admin/entities.ts create mode 100644 src/lib/api/crud.ts create mode 100644 src/lib/api/response.ts create mode 100644 src/lib/api/revalidate.ts create mode 100644 src/lib/auth/admin.ts create mode 100644 src/lib/data/admin/cms.ts create mode 100644 src/lib/data/admin/courses.ts create mode 100644 src/lib/data/admin/helpers.ts create mode 100644 src/lib/data/admin/registrations.ts create mode 100644 src/lib/data/articles.ts create mode 100644 src/lib/data/courses.ts create mode 100644 src/lib/data/events.ts create mode 100644 src/lib/data/programs.ts create mode 100644 src/lib/data/site.ts create mode 100644 src/lib/db.ts create mode 100644 src/lib/db/errors.ts create mode 100644 src/lib/db/mappers.ts create mode 100644 src/lib/images.ts create mode 100644 src/lib/labels.ts create mode 100644 src/lib/mock/articles.ts create mode 100644 src/lib/mock/courses.ts create mode 100644 src/lib/mock/events.ts create mode 100644 src/lib/mock/programs.ts create mode 100644 src/lib/mock/site.ts create mode 100644 src/lib/seo/json-ld.tsx create mode 100644 src/lib/site-config.ts create mode 100644 src/lib/types/index.ts create mode 100644 src/lib/utils.ts create mode 100644 src/lib/validation/admin.ts create mode 100644 src/lib/validation/public.ts create mode 100644 src/proxy.ts diff --git a/.agents/skills/design-system-rules/SKILL.md b/.agents/skills/design-system-rules/SKILL.md new file mode 100644 index 0000000..c011ef3 --- /dev/null +++ b/.agents/skills/design-system-rules/SKILL.md @@ -0,0 +1,28 @@ +--- +name: design-system-rules +description: >- + Project design-system rules for AUT Open Education: shadcn/ui + Tailwind only. + Use when changing UI, styling, colors, cards, navigation, forms, or loading + states. Read docs/design-system-rules.md and skill shadcn-ui before visual work. +--- + +# Design System Rules + +## Instructions + +1. **Before any UI change**, read: + - `docs/design-system-rules.md` + - skill `shadcn-ui` (`.agents/skills/shadcn-ui/SKILL.md`) + - Theme: `src/app/globals.css` (shadcn CSS variables only) +2. Build from `@/components/ui/*` + Tailwind. Add missing pieces with `npx shadcn@latest add`. +3. Colors: `bg-primary`, `text-muted-foreground`, `bg-muted`, `bg-chart-3` — never `ds-*` or `--brand-*`. +4. Extract substantial UI into molecules/organisms; keep pages thin (`.cursor/rules/ui-architecture.mdc`). +5. Material Design skill is methodology only — do not replace AUT colors mapped into shadcn tokens. +6. Complete the checklist in §4 of `docs/design-system-rules.md` before finishing. + +## Anti-patterns + +- Reviving `.ds-*` utilities or `--brand-*` parallel tokens +- Inventing new hex in components (use theme vars / SVG `var(--accent)`) +- Full section border boxes when `Card` / `Separator` / spacing suffice +- Physical `ml/mr/pl/pr` on RTL without an LTR island diff --git a/.agents/skills/material-design/SKILL.md b/.agents/skills/material-design/SKILL.md new file mode 100644 index 0000000..1a976f2 --- /dev/null +++ b/.agents/skills/material-design/SKILL.md @@ -0,0 +1,165 @@ +--- +name: material-design +description: >- + Material Design 3 / M3 Expressive principles, color roles, typography scale, + elevation, motion, and anti-patterns. Use when designing or reviewing UI, + building design tokens, choosing component patterns, accessibility defaults, + or when the user mentions Material, M3, design system foundation, or visual consistency. +--- +# Material Design + +## OVERVIEW +Google's comprehensive open-source design system providing guidelines, components, and tools for building high-quality digital experiences. Launched 2014, evolved to Material 3 (2021), Material 3 Expressive (2025). Unified approach across Android, web, iOS, and Flutter platforms. + +**Why this matters**: Accelerates development with pre-built components, ensures accessibility compliance, maintains cross-platform consistency, backed by extensive documentation and community support. + +## WHEN TO USE +- Designing Android applications (native design language) +- Creating cross-platform products requiring consistent experience +- Building design systems from established foundation +- Rapid prototyping with pre-built specifications +- Products requiring strong accessibility defaults (WCAG-compliant) +- Teams needing shared designer-developer vocabulary +- Brands wanting modern design without starting from scratch + +**Trigger**: Need to ship polished UI quickly or maintain consistency across multiple platforms. + +## KEY PRINCIPLES + +### 1. Material is the Metaphor +**Concept**: Digital elements behave like physical materials with tactile qualities, depth, and realistic motion. + +**Application**: +- Surfaces have elevation (z-axis positioning creating shadows) +- Elements respond to touch with ripple effects +- Transitions maintain spatial relationships +- Depth communicates hierarchy and focus + +**Implementation**: Cards at 2dp elevation, FAB at 6dp, navigation drawer at 16dp, modals at 24dp. + +### 2. Bold, Graphic, Intentional +**Concept**: Use vibrant colors, prominent typography, and deliberate white space to create clear visual hierarchy. + +**Application**: +- Dynamic color system generates cohesive palettes +- Typography scale with consistent hierarchy (Display, Headline, Title, Body, Label) +- Purposeful use of color to guide attention +- Generous spacing for clarity + +**Implementation**: Extract brand colors, generate 65 tokens (13 tones × 5 roles), apply type scale. + +### 3. Motion Provides Meaning +**Concept**: Animation is not decoration—it guides understanding and maintains context. + +**Application**: +- Spring physics for organic, responsive feel (Material 3 Expressive) +- Shared element transitions maintain spatial continuity +- Motion emphasizes hierarchy and relationships +- Respect prefers-reduced-motion for accessibility + +**Implementation**: Replace duration-based easing with spring animations, use morphing shapes. + +## EXECUTION STEPS + +### Phase 1: Establish Foundation +1. **Define color palette** - Use Theme Builder to extract from brand assets +2. **Set up typography scale** - Choose Display/Headline/Title/Body/Label sizes +3. **Configure shape system** - Define corner radius scale (None to Full) +4. **Implement elevation system** - Establish z-axis hierarchy + +### Phase 2: Build Component Library +5. **Import Material components** - Use Material UI (React), MDC-Web, or Flutter Material +6. **Customize theme tokens** - Override color, typography, shape as needed +7. **Test accessibility** - Verify contrast ratios, keyboard navigation, screen readers +8. **Create responsive layouts** - Apply 12-column grid with breakpoints (Compact/Medium/Expanded) + +### Phase 3: Implement Motion & Refinement +9. **Add spring physics** - Replace linear animations with organic motion +10. **Implement state changes** - Hover, focus, active, disabled states +11. **Test cross-platform** - Verify consistency across web/iOS/Android +12. **Document patterns** - Catalog custom implementations for team reference + +## SUCCESS METRICS +- **Development velocity** - 2-3x faster with pre-built components +- **Accessibility compliance** - WCAG AA/AAA pass rate ≥ 95% +- **Cross-platform consistency** - User recognition across platforms ≥ 85% +- **Design-dev handoff time** - 50%+ reduction vs. custom designs +- **User task completion** - Familiar patterns increase success rates + +## REAL-WORLD EXAMPLES + +### Google Photos +Comprehensive Material 3 implementation demonstrating dynamic color theming that adapts to user wallpaper. Spring animations for photo grid interactions. + +### Todoist +Cross-platform task manager using Material Design Web for consistency. Custom color theming while maintaining Material component patterns. + +### Cash App +Fintech product using Material elevation and components but customizing colors and shapes for brand differentiation. Passed accessibility audit first attempt. + +## ANTI-PATTERNS +**What NOT to do**: +- **Mixing design systems** - Combining Material with HIG or Fluent creates inconsistency +- **Arbitrary elevation** - Random z-axis values break hierarchy +- **Color without testing** - Skipping contrast ratio verification +- **Ignoring breakpoints** - Fixed layouts that break on tablets +- **Custom motion timing** - Replacing Material physics with linear easing +- **Recreating components** - Building from scratch vs. using libraries +- **Overriding accessibility** - Changing touch targets or keyboard navigation +- **Treating as rigid** - Material is flexible; customize thoughtfully + +## EDGE CASES +- **Strong brand identity** - Customize color/shape/typography but keep interaction patterns +- **iOS-first products** - Material works on iOS but consider HIG for platform conventions +- **High-security contexts** - Material's bold colors may conflict with conservative aesthetics +- **Low-bandwidth environments** - Material components can be heavy; consider lite versions +- **Highly specialized interfaces** - Complex data tools may need custom components + +## INTEGRATION +**Pairs well with**: +- **Design Tokens** - Material 3 built on token architecture +- **Atomic Design** - Component hierarchy methodology +- **Storybook** - Document Material components +- **Figma UI Kits** - Design with official Material templates +- **Accessibility Standards** - WCAG compliance built-in + +**Contrasts with**: +- **Human Interface Guidelines** - Apple's iOS/macOS design language +- **Fluent Design** - Microsoft's Windows design system +- **Custom design systems** - Bespoke vs. established framework + +## TOOLS & RESOURCES +- **Official site**: m3.material.io (comprehensive documentation) +- **Theme Builder**: Material Theme Builder (Figma plugin) +- **Component libraries**: Material UI (React), MDC-Web, Flutter Material +- **Design kits**: Official Figma/Sketch UI kits +- **Color tool**: Material palette generator +- **Motion guidelines**: Material motion system documentation + +## 2025 UPDATE: Material 3 Expressive +Announced at The Android Show (May 2025) for Android 16 and Wear OS 6: +- Spring-based physics replacing duration-based easing +- 35 new morphing shapes with fluid transitions +- Enhanced color expressiveness with more vibrant defaults +- Improved animation smoothness and responsiveness + +## FURTHER READING +- **Primary Source**: Material Design 3 documentation (m3.material.io) +- **Implementation**: Material Components libraries for each platform +- **Case Studies**: Google Design Medium publication +- **Related**: *Design Systems* by Alla Kholmatova +- **Advanced**: Building Design Systems (Brad Frost) + +## SCORING RATIONALE +**Total: 47/50** + +| Criterion | Score | Reasoning | +|-----------|-------|-----------| +| Practitioner | 10/10 | Google ships Material across all products; battle-tested at scale | +| Clarity | 10/10 | Comprehensive docs, code examples, design kits, clear specifications | +| ROI | 10/10 | 2-3x faster development, accessibility built-in, reduces design debt | +| Novelty | 7/10 | Innovative in 2014; now standard but evolving with Expressive | +| Cross-Domain | 10/10 | Works across web, mobile, desktop, wearables, automotive | + +**Evidence**: Billions of Android devices, adoption by non-Google products (Todoist, Cash App), open-source community, continuous evolution (Material 3 Expressive 2025). + diff --git a/.agents/skills/shadcn-ui/SKILL.md b/.agents/skills/shadcn-ui/SKILL.md new file mode 100644 index 0000000..dfc6d84 --- /dev/null +++ b/.agents/skills/shadcn-ui/SKILL.md @@ -0,0 +1,33 @@ +--- +name: shadcn-ui +description: >- + Use shadcn/ui + Tailwind only for this project's UI. Triggers on UI, styling, + components, cards, forms, navigation, theming, or when the user mentions + shadcn, ui/*, or design tokens. Do not invent parallel ds-* or --brand-* systems. +--- + +# shadcn/ui for AUT Management Website + +## Source of truth + +- Docs: https://ui.shadcn.com/docs/installation and https://ui.shadcn.com/docs/installation/next +- Config: `components.json` (style `base-nova`, CSS vars, RTL) +- Styles: `src/app/globals.css` — only Tailwind + `shadcn/tailwind.css` + theme CSS variables +- Primitives: `src/components/ui/*` via `npx shadcn@latest add ` + +## Rules + +1. Build UI from `@/components/ui/*` + Tailwind utilities only. +2. Colors: `bg-primary`, `text-muted-foreground`, `bg-muted`, `border-border`, `bg-card` — never `--brand-*` or `brand-*` classes. +3. Do not create or revive `.ds-*` utilities, SurfaceCard, or DotCta patterns. +4. Prefer `Card`, `Button`, `Separator`, `Sheet`, `NavigationMenu`, `Input`, `Label`, `Tabs`, `Skeleton`, `Badge`. +5. Add missing primitives with the CLI; do not hand-copy stale component APIs. +6. Keep Persian RTL (`dir="rtl"` on layout; `components.json` `"rtl": true`). +7. AUT identity lives only in shadcn theme variables (`--primary`, `--accent`, …). + +## Anti-patterns + +- Parallel design tokens (`--brand-*`, `ds-card`, `ds-hero`, `ds-cta`) +- Full section boxes with `border border-border` when spacing/`Separator`/`Card` suffice +- Always-on motion (ken-burns, default lift on every card) +--- diff --git a/.agents/skills/vercel-react-best-practices/AGENTS.md b/.agents/skills/vercel-react-best-practices/AGENTS.md new file mode 100644 index 0000000..4e340a5 --- /dev/null +++ b/.agents/skills/vercel-react-best-practices/AGENTS.md @@ -0,0 +1,3810 @@ +# React Best Practices + +**Version 1.0.0** +Vercel Engineering +January 2026 + +> **Note:** +> This document is mainly for agents and LLMs to follow when maintaining, +> generating, or refactoring React and Next.js codebases. Humans +> may also find it useful, but guidance here is optimized for automation +> and consistency by AI-assisted workflows. + +--- + +## Abstract + +Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation. + +--- + +## Table of Contents + +1. [Eliminating Waterfalls](#1-eliminating-waterfalls) — **CRITICAL** + - 1.1 [Check Cheap Conditions Before Async Flags](#11-check-cheap-conditions-before-async-flags) + - 1.2 [Defer Await Until Needed](#12-defer-await-until-needed) + - 1.3 [Dependency-Based Parallelization](#13-dependency-based-parallelization) + - 1.4 [Prevent Waterfall Chains in API Routes](#14-prevent-waterfall-chains-in-api-routes) + - 1.5 [Promise.all() for Independent Operations](#15-promiseall-for-independent-operations) + - 1.6 [Strategic Suspense Boundaries](#16-strategic-suspense-boundaries) +2. [Bundle Size Optimization](#2-bundle-size-optimization) — **CRITICAL** + - 2.1 [Avoid Barrel File Imports](#21-avoid-barrel-file-imports) + - 2.2 [Conditional Module Loading](#22-conditional-module-loading) + - 2.3 [Defer Non-Critical Third-Party Libraries](#23-defer-non-critical-third-party-libraries) + - 2.4 [Dynamic Imports for Heavy Components](#24-dynamic-imports-for-heavy-components) + - 2.5 [Prefer Statically Analyzable Paths](#25-prefer-statically-analyzable-paths) + - 2.6 [Preload Based on User Intent](#26-preload-based-on-user-intent) +3. [Server-Side Performance](#3-server-side-performance) — **HIGH** + - 3.1 [Authenticate Server Actions Like API Routes](#31-authenticate-server-actions-like-api-routes) + - 3.2 [Avoid Duplicate Serialization in RSC Props](#32-avoid-duplicate-serialization-in-rsc-props) + - 3.3 [Avoid Shared Module State for Request Data](#33-avoid-shared-module-state-for-request-data) + - 3.4 [Cross-Request LRU Caching](#34-cross-request-lru-caching) + - 3.5 [Hoist Static I/O to Module Level](#35-hoist-static-io-to-module-level) + - 3.6 [Minimize Serialization at RSC Boundaries](#36-minimize-serialization-at-rsc-boundaries) + - 3.7 [Parallel Data Fetching with Component Composition](#37-parallel-data-fetching-with-component-composition) + - 3.8 [Parallel Nested Data Fetching](#38-parallel-nested-data-fetching) + - 3.9 [Per-Request Deduplication with React.cache()](#39-per-request-deduplication-with-reactcache) + - 3.10 [Use after() for Non-Blocking Operations](#310-use-after-for-non-blocking-operations) +4. [Client-Side Data Fetching](#4-client-side-data-fetching) — **MEDIUM-HIGH** + - 4.1 [Deduplicate Global Event Listeners](#41-deduplicate-global-event-listeners) + - 4.2 [Use Passive Event Listeners for Scrolling Performance](#42-use-passive-event-listeners-for-scrolling-performance) + - 4.3 [Use SWR for Automatic Deduplication](#43-use-swr-for-automatic-deduplication) + - 4.4 [Version and Minimize localStorage Data](#44-version-and-minimize-localstorage-data) +5. [Re-render Optimization](#5-re-render-optimization) — **MEDIUM** + - 5.1 [Calculate Derived State During Rendering](#51-calculate-derived-state-during-rendering) + - 5.2 [Defer State Reads to Usage Point](#52-defer-state-reads-to-usage-point) + - 5.3 [Do not wrap a simple expression with a primitive result type in useMemo](#53-do-not-wrap-a-simple-expression-with-a-primitive-result-type-in-usememo) + - 5.4 [Don't Define Components Inside Components](#54-dont-define-components-inside-components) + - 5.5 [Extract Default Non-primitive Parameter Value from Memoized Component to Constant](#55-extract-default-non-primitive-parameter-value-from-memoized-component-to-constant) + - 5.6 [Extract to Memoized Components](#56-extract-to-memoized-components) + - 5.7 [Narrow Effect Dependencies](#57-narrow-effect-dependencies) + - 5.8 [Put Interaction Logic in Event Handlers](#58-put-interaction-logic-in-event-handlers) + - 5.9 [Split Combined Hook Computations](#59-split-combined-hook-computations) + - 5.10 [Subscribe to Derived State](#510-subscribe-to-derived-state) + - 5.11 [Use Functional setState Updates](#511-use-functional-setstate-updates) + - 5.12 [Use Lazy State Initialization](#512-use-lazy-state-initialization) + - 5.13 [Use Transitions for Non-Urgent Updates](#513-use-transitions-for-non-urgent-updates) + - 5.14 [Use useDeferredValue for Expensive Derived Renders](#514-use-usedeferredvalue-for-expensive-derived-renders) + - 5.15 [Use useRef for Transient Values](#515-use-useref-for-transient-values) +6. [Rendering Performance](#6-rendering-performance) — **MEDIUM** + - 6.1 [Animate SVG Wrapper Instead of SVG Element](#61-animate-svg-wrapper-instead-of-svg-element) + - 6.2 [CSS content-visibility for Long Lists](#62-css-content-visibility-for-long-lists) + - 6.3 [Hoist Static JSX Elements](#63-hoist-static-jsx-elements) + - 6.4 [Optimize SVG Precision](#64-optimize-svg-precision) + - 6.5 [Prevent Hydration Mismatch Without Flickering](#65-prevent-hydration-mismatch-without-flickering) + - 6.6 [Suppress Expected Hydration Mismatches](#66-suppress-expected-hydration-mismatches) + - 6.7 [Use Activity Component for Show/Hide](#67-use-activity-component-for-showhide) + - 6.8 [Use defer or async on Script Tags](#68-use-defer-or-async-on-script-tags) + - 6.9 [Use Explicit Conditional Rendering](#69-use-explicit-conditional-rendering) + - 6.10 [Use React DOM Resource Hints](#610-use-react-dom-resource-hints) + - 6.11 [Use useTransition Over Manual Loading States](#611-use-usetransition-over-manual-loading-states) +7. [JavaScript Performance](#7-javascript-performance) — **LOW-MEDIUM** + - 7.1 [Avoid Layout Thrashing](#71-avoid-layout-thrashing) + - 7.2 [Build Index Maps for Repeated Lookups](#72-build-index-maps-for-repeated-lookups) + - 7.3 [Cache Property Access in Loops](#73-cache-property-access-in-loops) + - 7.4 [Cache Repeated Function Calls](#74-cache-repeated-function-calls) + - 7.5 [Cache Storage API Calls](#75-cache-storage-api-calls) + - 7.6 [Combine Multiple Array Iterations](#76-combine-multiple-array-iterations) + - 7.7 [Defer Non-Critical Work with requestIdleCallback](#77-defer-non-critical-work-with-requestidlecallback) + - 7.8 [Early Length Check for Array Comparisons](#78-early-length-check-for-array-comparisons) + - 7.9 [Early Return from Functions](#79-early-return-from-functions) + - 7.10 [Hoist RegExp Creation](#710-hoist-regexp-creation) + - 7.11 [Use flatMap to Map and Filter in One Pass](#711-use-flatmap-to-map-and-filter-in-one-pass) + - 7.12 [Use Loop for Min/Max Instead of Sort](#712-use-loop-for-minmax-instead-of-sort) + - 7.13 [Use Set/Map for O(1) Lookups](#713-use-setmap-for-o1-lookups) + - 7.14 [Use toSorted() Instead of sort() for Immutability](#714-use-tosorted-instead-of-sort-for-immutability) +8. [Advanced Patterns](#8-advanced-patterns) — **LOW** + - 8.1 [Do Not Put Effect Events in Dependency Arrays](#81-do-not-put-effect-events-in-dependency-arrays) + - 8.2 [Initialize App Once, Not Per Mount](#82-initialize-app-once-not-per-mount) + - 8.3 [Store Event Handlers in Refs](#83-store-event-handlers-in-refs) + - 8.4 [useEffectEvent for Stable Callback Refs](#84-useeffectevent-for-stable-callback-refs) + +--- + +## 1. Eliminating Waterfalls + +**Impact: CRITICAL** + +Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains. + +### 1.1 Check Cheap Conditions Before Async Flags + +**Impact: HIGH (avoids unnecessary async work when a synchronous guard already fails)** + +When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true. + +This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks. + +**Incorrect:** + +```typescript +const someFlag = await getFlag() + +if (someFlag && someCondition) { + // ... +} +``` + +**Correct:** + +```typescript +if (someCondition) { + const someFlag = await getFlag() + if (someFlag) { + // ... + } +} +``` + +This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path. + +Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order. + +### 1.2 Defer Await Until Needed + +**Impact: HIGH (avoids blocking unused code paths)** + +Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them. + +**Incorrect: blocks both branches** + +```typescript +async function handleRequest(userId: string, skipProcessing: boolean) { + const userData = await fetchUserData(userId) + + if (skipProcessing) { + // Returns immediately but still waited for userData + return { skipped: true } + } + + // Only this branch uses userData + return processUserData(userData) +} +``` + +**Correct: only blocks when needed** + +```typescript +async function handleRequest(userId: string, skipProcessing: boolean) { + if (skipProcessing) { + // Returns immediately without waiting + return { skipped: true } + } + + // Fetch only when needed + const userData = await fetchUserData(userId) + return processUserData(userData) +} +``` + +**Another example: early return optimization** + +```typescript +// Incorrect: always fetches permissions +async function updateResource(resourceId: string, userId: string) { + const permissions = await fetchPermissions(userId) + const resource = await getResource(resourceId) + + if (!resource) { + return { error: 'Not found' } + } + + if (!permissions.canEdit) { + return { error: 'Forbidden' } + } + + return await updateResourceData(resource, permissions) +} + +// Correct: fetches only when needed +async function updateResource(resourceId: string, userId: string) { + const resource = await getResource(resourceId) + + if (!resource) { + return { error: 'Not found' } + } + + const permissions = await fetchPermissions(userId) + + if (!permissions.canEdit) { + return { error: 'Forbidden' } + } + + return await updateResourceData(resource, permissions) +} +``` + +This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive. + +For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md). + +### 1.3 Dependency-Based Parallelization + +**Impact: CRITICAL (2-10× improvement)** + +For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment. + +**Incorrect: profile waits for config unnecessarily** + +```typescript +const [user, config] = await Promise.all([ + fetchUser(), + fetchConfig() +]) +const profile = await fetchProfile(user.id) +``` + +**Correct: config and profile run in parallel** + +```typescript +import { all } from 'better-all' + +const { user, config, profile } = await all({ + async user() { return fetchUser() }, + async config() { return fetchConfig() }, + async profile() { + return fetchProfile((await this.$.user).id) + } +}) +``` + +**Alternative without extra dependencies:** + +```typescript +const userPromise = fetchUser() +const profilePromise = userPromise.then(user => fetchProfile(user.id)) + +const [user, config, profile] = await Promise.all([ + userPromise, + fetchConfig(), + profilePromise +]) +``` + +We can also create all the promises first, and do `Promise.all()` at the end. + +Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all) + +### 1.4 Prevent Waterfall Chains in API Routes + +**Impact: CRITICAL (2-10× improvement)** + +In API routes and Server Actions, start independent operations immediately, even if you don't await them yet. + +**Incorrect: config waits for auth, data waits for both** + +```typescript +export async function GET(request: Request) { + const session = await auth() + const config = await fetchConfig() + const data = await fetchData(session.user.id) + return Response.json({ data, config }) +} +``` + +**Correct: auth and config start immediately** + +```typescript +export async function GET(request: Request) { + const sessionPromise = auth() + const configPromise = fetchConfig() + const session = await sessionPromise + const [config, data] = await Promise.all([ + configPromise, + fetchData(session.user.id) + ]) + return Response.json({ data, config }) +} +``` + +For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization). + +### 1.5 Promise.all() for Independent Operations + +**Impact: CRITICAL (2-10× improvement)** + +When async operations have no interdependencies, execute them concurrently using `Promise.all()`. + +**Incorrect: sequential execution, 3 round trips** + +```typescript +const user = await fetchUser() +const posts = await fetchPosts() +const comments = await fetchComments() +``` + +**Correct: parallel execution, 1 round trip** + +```typescript +const [user, posts, comments] = await Promise.all([ + fetchUser(), + fetchPosts(), + fetchComments() +]) +``` + +### 1.6 Strategic Suspense Boundaries + +**Impact: HIGH (faster initial paint)** + +Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads. + +**Incorrect: wrapper blocked by data fetching** + +```tsx +async function Page() { + const data = await fetchData() // Blocks entire page + + return ( +
+
Sidebar
+
Header
+
+ +
+
Footer
+
+ ) +} +``` + +The entire layout waits for data even though only the middle section needs it. + +**Correct: wrapper shows immediately, data streams in** + +```tsx +function Page() { + return ( +
+
Sidebar
+
Header
+
+ }> + + +
+
Footer
+
+ ) +} + +async function DataDisplay() { + const data = await fetchData() // Only blocks this component + return
{data.content}
+} +``` + +Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data. + +**Alternative: share promise across components** + +```tsx +function Page() { + // Start fetch immediately, but don't await + const dataPromise = fetchData() + + return ( +
+
Sidebar
+
Header
+ }> + + + +
Footer
+
+ ) +} + +function DataDisplay({ dataPromise }: { dataPromise: Promise }) { + const data = use(dataPromise) // Unwraps the promise + return
{data.content}
+} + +function DataSummary({ dataPromise }: { dataPromise: Promise }) { + const data = use(dataPromise) // Reuses the same promise + return
{data.summary}
+} +``` + +Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together. + +**When NOT to use this pattern:** + +- Critical data needed for layout decisions (affects positioning) + +- SEO-critical content above the fold + +- Small, fast queries where suspense overhead isn't worth it + +- When you want to avoid layout shift (loading → content jump) + +**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities. + +--- + +## 2. Bundle Size Optimization + +**Impact: CRITICAL** + +Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint. + +### 2.1 Avoid Barrel File Imports + +**Impact: CRITICAL (200-800ms import cost, slow builds)** + +Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`). + +Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts. + +**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph. + +**Incorrect: imports entire library** + +```tsx +import { Check, X, Menu } from 'lucide-react' +// Loads 1,583 modules, takes ~2.8s extra in dev +// Runtime cost: 200-800ms on every cold start + +import { Button, TextField } from '@mui/material' +// Loads 2,225 modules, takes ~4.2s extra in dev +``` + +**Correct - Next.js 13.5+ (recommended):** + +```tsx +// Keep the standard imports - Next.js transforms them to direct imports +import { Check, X, Menu } from 'lucide-react' +// Full TypeScript support, no manual path wrangling +``` + +This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost. + +**Correct - Direct imports (non-Next.js projects):** + +```tsx +import Button from '@mui/material/Button' +import TextField from '@mui/material/TextField' +// Loads only what you use +``` + +> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports. + +These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR. + +Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`. + +Reference: [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js) + +### 2.2 Conditional Module Loading + +**Impact: HIGH (loads large data only when needed)** + +Load large data or modules only when a feature is activated. + +**Example: lazy-load animation frames** + +```tsx +function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch> }) { + const [frames, setFrames] = useState(null) + + useEffect(() => { + if (enabled && !frames && typeof window !== 'undefined') { + import('./animation-frames.js') + .then(mod => setFrames(mod.frames)) + .catch(() => setEnabled(false)) + } + }, [enabled, frames, setEnabled]) + + if (!frames) return + return +} +``` + +The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed. + +### 2.3 Defer Non-Critical Third-Party Libraries + +**Impact: MEDIUM (loads after hydration)** + +Analytics, logging, and error tracking don't block user interaction. Load them after hydration. + +**Incorrect: blocks initial bundle** + +```tsx +import { Analytics } from '@vercel/analytics/react' + +export default function RootLayout({ children }) { + return ( + + + {children} + + + + ) +} +``` + +**Correct: loads after hydration** + +```tsx +import dynamic from 'next/dynamic' + +const Analytics = dynamic( + () => import('@vercel/analytics/react').then(m => m.Analytics), + { ssr: false } +) + +export default function RootLayout({ children }) { + return ( + + + {children} + + + + ) +} +``` + +### 2.4 Dynamic Imports for Heavy Components + +**Impact: CRITICAL (directly affects TTI and LCP)** + +Use `next/dynamic` to lazy-load large components not needed on initial render. + +**Incorrect: Monaco bundles with main chunk ~300KB** + +```tsx +import { MonacoEditor } from './monaco-editor' + +function CodePanel({ code }: { code: string }) { + return +} +``` + +**Correct: Monaco loads on demand** + +```tsx +import dynamic from 'next/dynamic' + +const MonacoEditor = dynamic( + () => import('./monaco-editor').then(m => m.MonacoEditor), + { ssr: false } +) + +function CodePanel({ code }: { code: string }) { + return +} +``` + +### 2.5 Prefer Statically Analyzable Paths + +**Impact: HIGH (avoids accidental broad bundles and file traces)** + +Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe. + +Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code. + +When analysis becomes too broad, the cost is real: + +- Larger server bundles + +- Slower builds + +- Worse cold starts + +- More memory use + +**Incorrect: the bundler cannot tell what may be imported** + +```ts +const PAGE_MODULES = { + home: './pages/home', + settings: './pages/settings', +} as const + +const Page = await import(PAGE_MODULES[pageName]) +``` + +**Correct: use an explicit map of allowed modules** + +```ts +const PAGE_MODULES = { + home: () => import('./pages/home'), + settings: () => import('./pages/settings'), +} as const + +const Page = await PAGE_MODULES[pageName]() +``` + +**Incorrect: a 2-value enum still hides the final path from static analysis** + +```ts +const baseDir = path.join(process.cwd(), 'content/' + contentKind) +``` + +**Correct: make each final path literal at the callsite** + +```ts +const baseDir = + kind === ContentKind.Blog + ? path.join(process.cwd(), 'content/blog') + : path.join(process.cwd(), 'content/docs') +``` + +In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage. + +Reference: [https://nextjs.org/docs/app/api-reference/config/next-config-js/output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [https://nextjs.org/learn/seo/dynamic-imports](https://nextjs.org/learn/seo/dynamic-imports), [https://vite.dev/guide/features.html](https://vite.dev/guide/features.html), [https://esbuild.github.io/api/](https://esbuild.github.io/api/), [https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [https://webpack.js.org/guides/dependency-management/](https://webpack.js.org/guides/dependency-management/) + +### 2.6 Preload Based on User Intent + +**Impact: MEDIUM (reduces perceived latency)** + +Preload heavy bundles before they're needed to reduce perceived latency. + +**Example: preload on hover/focus** + +```tsx +function EditorButton({ onClick }: { onClick: () => void }) { + const preload = () => { + if (typeof window !== 'undefined') { + void import('./monaco-editor') + } + } + + return ( + + ) +} +``` + +**Example: preload when feature flag is enabled** + +```tsx +function FlagsProvider({ children, flags }: Props) { + useEffect(() => { + if (flags.editorEnabled && typeof window !== 'undefined') { + void import('./monaco-editor').then(mod => mod.init()) + } + }, [flags.editorEnabled]) + + return + {children} + +} +``` + +The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed. + +--- + +## 3. Server-Side Performance + +**Impact: HIGH** + +Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times. + +### 3.1 Authenticate Server Actions Like API Routes + +**Impact: CRITICAL (prevents unauthorized access to server mutations)** + +Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly. + +Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation." + +**Incorrect: no authentication check** + +```typescript +'use server' + +export async function deleteUser(userId: string) { + // Anyone can call this! No auth check + await db.user.delete({ where: { id: userId } }) + return { success: true } +} +``` + +**Correct: authentication inside the action** + +```typescript +'use server' + +import { verifySession } from '@/lib/auth' +import { unauthorized } from '@/lib/errors' + +export async function deleteUser(userId: string) { + // Always check auth inside the action + const session = await verifySession() + + if (!session) { + throw unauthorized('Must be logged in') + } + + // Check authorization too + if (session.user.role !== 'admin' && session.user.id !== userId) { + throw unauthorized('Cannot delete other users') + } + + await db.user.delete({ where: { id: userId } }) + return { success: true } +} +``` + +**With input validation:** + +```typescript +'use server' + +import { verifySession } from '@/lib/auth' +import { z } from 'zod' + +const updateProfileSchema = z.object({ + userId: z.string().uuid(), + name: z.string().min(1).max(100), + email: z.string().email() +}) + +export async function updateProfile(data: unknown) { + // Validate input first + const validated = updateProfileSchema.parse(data) + + // Then authenticate + const session = await verifySession() + if (!session) { + throw new Error('Unauthorized') + } + + // Then authorize + if (session.user.id !== validated.userId) { + throw new Error('Can only update own profile') + } + + // Finally perform the mutation + await db.user.update({ + where: { id: validated.userId }, + data: { + name: validated.name, + email: validated.email + } + }) + + return { success: true } +} +``` + +Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication) + +### 3.2 Avoid Duplicate Serialization in RSC Props + +**Impact: LOW (reduces network payload by avoiding duplicate serialization)** + +RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server. + +**Incorrect: duplicates array** + +```tsx +// RSC: sends 6 strings (2 arrays × 3 items) + +``` + +**Correct: sends 3 strings** + +```tsx +// RSC: send once + + +// Client: transform there +'use client' +const sorted = useMemo(() => [...usernames].sort(), [usernames]) +``` + +**Nested deduplication behavior:** + +```tsx +// string[] - duplicates everything +usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings + +// object[] - duplicates array structure only +users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4) +``` + +Deduplication works recursively. Impact varies by data type: + +- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated + +- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference + +**Operations breaking deduplication: create new references** + +- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]` + +- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())` + +**More examples:** + +```tsx +// ❌ Bad + u.active)} /> + + +// ✅ Good + + +// Do filtering/destructuring in client +``` + +**Exception:** Pass derived data when transformation is expensive or client doesn't need original. + +### 3.3 Avoid Shared Module State for Request Data + +**Impact: HIGH (prevents concurrency bugs and request data leaks)** + +For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response. + +Treat module scope on the server as process-wide shared memory, not request-local state. + +**Incorrect: request data leaks across concurrent renders** + +```tsx +let currentUser: User | null = null + +export default async function Page() { + currentUser = await auth() + return +} + +async function Dashboard() { + return
{currentUser?.name}
+} +``` + +If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`. + +**Correct: keep request data local to the render tree** + +```tsx +export default async function Page() { + const user = await auth() + return +} + +function Dashboard({ user }: { user: User | null }) { + return
{user?.name}
+} +``` + +Safe exceptions: + +- Immutable static assets or config loaded once at module scope + +- Shared caches intentionally designed for cross-request reuse and keyed correctly + +- Process-wide singletons that do not store request- or user-specific mutable data + +For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md). + +### 3.4 Cross-Request LRU Caching + +**Impact: HIGH (caches across requests)** + +`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache. + +**Implementation:** + +```typescript +import { LRUCache } from 'lru-cache' + +const cache = new LRUCache({ + max: 1000, + ttl: 5 * 60 * 1000 // 5 minutes +}) + +export async function getUser(id: string) { + const cached = cache.get(id) + if (cached) return cached + + const user = await db.user.findUnique({ where: { id } }) + cache.set(id, user) + return user +} + +// Request 1: DB query, result cached +// Request 2: cache hit, no DB query +``` + +Use when sequential user actions hit multiple endpoints needing the same data within seconds. + +**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis. + +**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching. + +Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache) + +### 3.5 Hoist Static I/O to Module Level + +**Impact: HIGH (avoids repeated file/network I/O per request)** + +When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation. + +**Incorrect: reads font file on every request** + +```typescript +// app/api/og/route.tsx +import { ImageResponse } from 'next/og' + +export async function GET(request: Request) { + // Runs on EVERY request - expensive! + const fontData = await fetch( + new URL('./fonts/Inter.ttf', import.meta.url) + ).then(res => res.arrayBuffer()) + + const logoData = await fetch( + new URL('./images/logo.png', import.meta.url) + ).then(res => res.arrayBuffer()) + + return new ImageResponse( +
+ + Hello World +
, + { fonts: [{ name: 'Inter', data: fontData }] } + ) +} +``` + +**Correct: loads once at module initialization** + +```typescript +// app/api/og/route.tsx +import { ImageResponse } from 'next/og' + +// Module-level: runs ONCE when module is first imported +const fontData = fetch( + new URL('./fonts/Inter.ttf', import.meta.url) +).then(res => res.arrayBuffer()) + +const logoData = fetch( + new URL('./images/logo.png', import.meta.url) +).then(res => res.arrayBuffer()) + +export async function GET(request: Request) { + // Await the already-started promises + const [font, logo] = await Promise.all([fontData, logoData]) + + return new ImageResponse( +
+ + Hello World +
, + { fonts: [{ name: 'Inter', data: font }] } + ) +} +``` + +**Correct: synchronous fs at module level** + +```typescript +// app/api/og/route.tsx +import { ImageResponse } from 'next/og' +import { readFileSync } from 'fs' +import { join } from 'path' + +// Synchronous read at module level - blocks only during module init +const fontData = readFileSync( + join(process.cwd(), 'public/fonts/Inter.ttf') +) + +const logoData = readFileSync( + join(process.cwd(), 'public/images/logo.png') +) + +export async function GET(request: Request) { + return new ImageResponse( +
+ + Hello World +
, + { fonts: [{ name: 'Inter', data: fontData }] } + ) +} +``` + +**Incorrect: reads config on every call** + +```typescript +import fs from 'node:fs/promises' + +export async function processRequest(data: Data) { + const config = JSON.parse( + await fs.readFile('./config.json', 'utf-8') + ) + const template = await fs.readFile('./template.html', 'utf-8') + + return render(template, data, config) +} +``` + +**Correct: hoists config and template to module level** + +```typescript +import fs from 'node:fs/promises' + +const configPromise = fs + .readFile('./config.json', 'utf-8') + .then(JSON.parse) +const templatePromise = fs.readFile('./template.html', 'utf-8') + +export async function processRequest(data: Data) { + const [config, template] = await Promise.all([ + configPromise, + templatePromise, + ]) + + return render(template, data, config) +} +``` + +When to use this pattern: + +- Loading fonts for OG image generation + +- Loading static logos, icons, or watermarks + +- Reading configuration files that don't change at runtime + +- Loading email templates or other static templates + +- Any static asset that's the same across all requests + +When not to use this pattern: + +- Assets that vary per request or user + +- Files that may change during runtime (use caching with TTL instead) + +- Large files that would consume too much memory if kept loaded + +- Sensitive data that shouldn't persist in memory + +With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties. + +In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled. + +### 3.6 Minimize Serialization at RSC Boundaries + +**Impact: HIGH (reduces data transfer size)** + +The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses. + +**Incorrect: serializes all 50 fields** + +```tsx +async function Page() { + const user = await fetchUser() // 50 fields + return +} + +'use client' +function Profile({ user }: { user: User }) { + return
{user.name}
// uses 1 field +} +``` + +**Correct: serializes only 1 field** + +```tsx +async function Page() { + const user = await fetchUser() + return +} + +'use client' +function Profile({ name }: { name: string }) { + return
{name}
+} +``` + +### 3.7 Parallel Data Fetching with Component Composition + +**Impact: CRITICAL (eliminates server-side waterfalls)** + +React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching. + +**Incorrect: Sidebar waits for Page's fetch to complete** + +```tsx +export default async function Page() { + const header = await fetchHeader() + return ( +
+
{header}
+ +
+ ) +} + +async function Sidebar() { + const items = await fetchSidebarItems() + return +} +``` + +**Correct: both fetch simultaneously** + +```tsx +async function Header() { + const data = await fetchHeader() + return
{data}
+} + +async function Sidebar() { + const items = await fetchSidebarItems() + return +} + +export default function Page() { + return ( +
+
+ +
+ ) +} +``` + +**Alternative with children prop:** + +```tsx +async function Header() { + const data = await fetchHeader() + return
{data}
+} + +async function Sidebar() { + const items = await fetchSidebarItems() + return +} + +function Layout({ children }: { children: ReactNode }) { + return ( +
+
+ {children} +
+ ) +} + +export default function Page() { + return ( + + + + ) +} +``` + +### 3.8 Parallel Nested Data Fetching + +**Impact: CRITICAL (eliminates server-side waterfalls)** + +When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest. + +**Incorrect: a single slow item blocks all nested fetches** + +```tsx +const chats = await Promise.all( + chatIds.map(id => getChat(id)) +) + +const chatAuthors = await Promise.all( + chats.map(chat => getUser(chat.author)) +) +``` + +If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready. + +**Correct: each item chains its own nested fetch** + +```tsx +const chatAuthors = await Promise.all( + chatIds.map(id => getChat(id).then(chat => getUser(chat.author))) +) +``` + +Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others. + +### 3.9 Per-Request Deduplication with React.cache() + +**Impact: MEDIUM (deduplicates within request)** + +Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most. + +**Usage:** + +```typescript +import { cache } from 'react' + +export const getCurrentUser = cache(async () => { + const session = await auth() + if (!session?.user?.id) return null + return await db.user.findUnique({ + where: { id: session.user.id } + }) +}) +``` + +Within a single request, multiple calls to `getCurrentUser()` execute the query only once. + +**Avoid inline objects as arguments:** + +`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits. + +**Incorrect: always cache miss** + +```typescript +const getUser = cache(async (params: { uid: number }) => { + return await db.user.findUnique({ where: { id: params.uid } }) +}) + +// Each call creates new object, never hits cache +getUser({ uid: 1 }) +getUser({ uid: 1 }) // Cache miss, runs query again +``` + +**Correct: cache hit** + +```typescript +const params = { uid: 1 } +getUser(params) // Query runs +getUser(params) // Cache hit (same reference) +``` + +If you must pass objects, pass the same reference: + +**Next.js-Specific Note:** + +In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks: + +- Database queries (Prisma, Drizzle, etc.) + +- Heavy computations + +- Authentication checks + +- File system operations + +- Any non-fetch async work + +Use `React.cache()` to deduplicate these operations across your component tree. + +Reference: [https://react.dev/reference/react/cache](https://react.dev/reference/react/cache) + +### 3.10 Use after() for Non-Blocking Operations + +**Impact: MEDIUM (faster response times)** + +Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response. + +**Incorrect: blocks response** + +```tsx +import { logUserAction } from '@/app/utils' + +export async function POST(request: Request) { + // Perform mutation + await updateDatabase(request) + + // Logging blocks the response + const userAgent = request.headers.get('user-agent') || 'unknown' + await logUserAction({ userAgent }) + + return new Response(JSON.stringify({ status: 'success' }), { + status: 200, + headers: { 'Content-Type': 'application/json' } + }) +} +``` + +**Correct: non-blocking** + +```tsx +import { after } from 'next/server' +import { headers, cookies } from 'next/headers' +import { logUserAction } from '@/app/utils' + +export async function POST(request: Request) { + // Perform mutation + await updateDatabase(request) + + // Log after response is sent + after(async () => { + const userAgent = (await headers()).get('user-agent') || 'unknown' + const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous' + + logUserAction({ sessionCookie, userAgent }) + }) + + return new Response(JSON.stringify({ status: 'success' }), { + status: 200, + headers: { 'Content-Type': 'application/json' } + }) +} +``` + +The response is sent immediately while logging happens in the background. + +**Common use cases:** + +- Analytics tracking + +- Audit logging + +- Sending notifications + +- Cache invalidation + +- Cleanup tasks + +**Important notes:** + +- `after()` runs even if the response fails or redirects + +- Works in Server Actions, Route Handlers, and Server Components + +Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after) + +--- + +## 4. Client-Side Data Fetching + +**Impact: MEDIUM-HIGH** + +Automatic deduplication and efficient data fetching patterns reduce redundant network requests. + +### 4.1 Deduplicate Global Event Listeners + +**Impact: LOW (single listener for N components)** + +Use `useSWRSubscription()` to share global event listeners across component instances. + +**Incorrect: N instances = N listeners** + +```tsx +function useKeyboardShortcut(key: string, callback: () => void) { + useEffect(() => { + const handler = (e: KeyboardEvent) => { + if (e.metaKey && e.key === key) { + callback() + } + } + window.addEventListener('keydown', handler) + return () => window.removeEventListener('keydown', handler) + }, [key, callback]) +} +``` + +When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener. + +**Correct: N instances = 1 listener** + +```tsx +import useSWRSubscription from 'swr/subscription' + +// Module-level Map to track callbacks per key +const keyCallbacks = new Map void>>() + +function useKeyboardShortcut(key: string, callback: () => void) { + // Register this callback in the Map + useEffect(() => { + if (!keyCallbacks.has(key)) { + keyCallbacks.set(key, new Set()) + } + keyCallbacks.get(key)!.add(callback) + + return () => { + const set = keyCallbacks.get(key) + if (set) { + set.delete(callback) + if (set.size === 0) { + keyCallbacks.delete(key) + } + } + } + }, [key, callback]) + + useSWRSubscription('global-keydown', () => { + const handler = (e: KeyboardEvent) => { + if (e.metaKey && keyCallbacks.has(e.key)) { + keyCallbacks.get(e.key)!.forEach(cb => cb()) + } + } + window.addEventListener('keydown', handler) + return () => window.removeEventListener('keydown', handler) + }) +} + +function Profile() { + // Multiple shortcuts will share the same listener + useKeyboardShortcut('p', () => { /* ... */ }) + useKeyboardShortcut('k', () => { /* ... */ }) + // ... +} +``` + +### 4.2 Use Passive Event Listeners for Scrolling Performance + +**Impact: MEDIUM (eliminates scroll delay caused by event listeners)** + +Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay. + +**Incorrect:** + +```typescript +useEffect(() => { + const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX) + const handleWheel = (e: WheelEvent) => console.log(e.deltaY) + + document.addEventListener('touchstart', handleTouch) + document.addEventListener('wheel', handleWheel) + + return () => { + document.removeEventListener('touchstart', handleTouch) + document.removeEventListener('wheel', handleWheel) + } +}, []) +``` + +**Correct:** + +```typescript +useEffect(() => { + const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX) + const handleWheel = (e: WheelEvent) => console.log(e.deltaY) + + document.addEventListener('touchstart', handleTouch, { passive: true }) + document.addEventListener('wheel', handleWheel, { passive: true }) + + return () => { + document.removeEventListener('touchstart', handleTouch) + document.removeEventListener('wheel', handleWheel) + } +}, []) +``` + +**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`. + +**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`. + +### 4.3 Use SWR for Automatic Deduplication + +**Impact: MEDIUM-HIGH (automatic deduplication)** + +SWR enables request deduplication, caching, and revalidation across component instances. + +**Incorrect: no deduplication, each instance fetches** + +```tsx +function UserList() { + const [users, setUsers] = useState([]) + useEffect(() => { + fetch('/api/users') + .then(r => r.json()) + .then(setUsers) + }, []) +} +``` + +**Correct: multiple instances share one request** + +```tsx +import useSWR from 'swr' + +function UserList() { + const { data: users } = useSWR('/api/users', fetcher) +} +``` + +**For immutable data:** + +```tsx +import { useImmutableSWR } from '@/lib/swr' + +function StaticContent() { + const { data } = useImmutableSWR('/api/config', fetcher) +} +``` + +**For mutations:** + +```tsx +import { useSWRMutation } from 'swr/mutation' + +function UpdateButton() { + const { trigger } = useSWRMutation('/api/user', updateUser) + return +} +``` + +Reference: [https://swr.vercel.app](https://swr.vercel.app) + +### 4.4 Version and Minimize localStorage Data + +**Impact: MEDIUM (prevents schema conflicts, reduces storage size)** + +Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data. + +**Incorrect:** + +```typescript +// No version, stores everything, no error handling +localStorage.setItem('userConfig', JSON.stringify(fullUserObject)) +const data = localStorage.getItem('userConfig') +``` + +**Correct:** + +```typescript +const VERSION = 'v2' + +function saveConfig(config: { theme: string; language: string }) { + try { + localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config)) + } catch { + // Throws in incognito/private browsing, quota exceeded, or disabled + } +} + +function loadConfig() { + try { + const data = localStorage.getItem(`userConfig:${VERSION}`) + return data ? JSON.parse(data) : null + } catch { + return null + } +} + +// Migration from v1 to v2 +function migrate() { + try { + const v1 = localStorage.getItem('userConfig:v1') + if (v1) { + const old = JSON.parse(v1) + saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang }) + localStorage.removeItem('userConfig:v1') + } + } catch {} +} +``` + +**Store minimal fields from server responses:** + +```typescript +// User object has 20+ fields, only store what UI needs +function cachePrefs(user: FullUser) { + try { + localStorage.setItem('prefs:v1', JSON.stringify({ + theme: user.preferences.theme, + notifications: user.preferences.notifications + })) + } catch {} +} +``` + +**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled. + +**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags. + +--- + +## 5. Re-render Optimization + +**Impact: MEDIUM** + +Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness. + +### 5.1 Calculate Derived State During Rendering + +**Impact: MEDIUM (avoids redundant renders and state drift)** + +If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead. + +**Incorrect: redundant state and effect** + +```tsx +function Form() { + const [firstName, setFirstName] = useState('First') + const [lastName, setLastName] = useState('Last') + const [fullName, setFullName] = useState('') + + useEffect(() => { + setFullName(firstName + ' ' + lastName) + }, [firstName, lastName]) + + return

{fullName}

+} +``` + +**Correct: derive during render** + +```tsx +function Form() { + const [firstName, setFirstName] = useState('First') + const [lastName, setLastName] = useState('Last') + const fullName = firstName + ' ' + lastName + + return

{fullName}

+} +``` + +Reference: [https://react.dev/learn/you-might-not-need-an-effect](https://react.dev/learn/you-might-not-need-an-effect) + +### 5.2 Defer State Reads to Usage Point + +**Impact: MEDIUM (avoids unnecessary subscriptions)** + +Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks. + +**Incorrect: subscribes to all searchParams changes** + +```tsx +function ShareButton({ chatId }: { chatId: string }) { + const searchParams = useSearchParams() + + const handleShare = () => { + const ref = searchParams.get('ref') + shareChat(chatId, { ref }) + } + + return +} +``` + +**Correct: reads on demand, no subscription** + +```tsx +function ShareButton({ chatId }: { chatId: string }) { + const handleShare = () => { + const params = new URLSearchParams(window.location.search) + const ref = params.get('ref') + shareChat(chatId, { ref }) + } + + return +} +``` + +### 5.3 Do not wrap a simple expression with a primitive result type in useMemo + +**Impact: LOW-MEDIUM (wasted computation on every render)** + +When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`. + +Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself. + +**Incorrect:** + +```tsx +function Header({ user, notifications }: Props) { + const isLoading = useMemo(() => { + return user.isLoading || notifications.isLoading + }, [user.isLoading, notifications.isLoading]) + + if (isLoading) return + // return some markup +} +``` + +**Correct:** + +```tsx +function Header({ user, notifications }: Props) { + const isLoading = user.isLoading || notifications.isLoading + + if (isLoading) return + // return some markup +} +``` + +### 5.4 Don't Define Components Inside Components + +**Impact: HIGH (prevents remount on every render)** + +Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM. + +A common reason developers do this is to access parent variables without passing props. Always pass props instead. + +**Incorrect: remounts on every render** + +```tsx +function UserProfile({ user, theme }) { + // Defined inside to access `theme` - BAD + const Avatar = () => ( + + ) + + // Defined inside to access `user` - BAD + const Stats = () => ( +
+ {user.followers} followers + {user.posts} posts +
+ ) + + return ( +
+ + +
+ ) +} +``` + +Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes. + +**Correct: pass props instead** + +```tsx +function Avatar({ src, theme }: { src: string; theme: string }) { + return ( + + ) +} + +function Stats({ followers, posts }: { followers: number; posts: number }) { + return ( +
+ {followers} followers + {posts} posts +
+ ) +} + +function UserProfile({ user, theme }) { + return ( +
+ + +
+ ) +} +``` + +**Symptoms of this bug:** + +- Input fields lose focus on every keystroke + +- Animations restart unexpectedly + +- `useEffect` cleanup/setup runs on every parent render + +- Scroll position resets inside the component + +### 5.5 Extract Default Non-primitive Parameter Value from Memoized Component to Constant + +**Impact: MEDIUM (restores memoization by using a constant for default value)** + +When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`. + +To address this issue, extract the default value into a constant. + +**Incorrect: `onClick` has different values on every rerender** + +```tsx +const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) { + // ... +}) + +// Used without optional onClick + +``` + +**Correct: stable default value** + +```tsx +const NOOP = () => {}; + +const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) { + // ... +}) + +// Used without optional onClick + +``` + +### 5.6 Extract to Memoized Components + +**Impact: MEDIUM (enables early returns)** + +Extract expensive work into memoized components to enable early returns before computation. + +**Incorrect: computes avatar even when loading** + +```tsx +function Profile({ user, loading }: Props) { + const avatar = useMemo(() => { + const id = computeAvatarId(user) + return + }, [user]) + + if (loading) return + return
{avatar}
+} +``` + +**Correct: skips computation when loading** + +```tsx +const UserAvatar = memo(function UserAvatar({ user }: { user: User }) { + const id = useMemo(() => computeAvatarId(user), [user]) + return +}) + +function Profile({ user, loading }: Props) { + if (loading) return + return ( +
+ +
+ ) +} +``` + +**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders. + +### 5.7 Narrow Effect Dependencies + +**Impact: LOW (minimizes effect re-runs)** + +Specify primitive dependencies instead of objects to minimize effect re-runs. + +**Incorrect: re-runs on any user field change** + +```tsx +useEffect(() => { + console.log(user.id) +}, [user]) +``` + +**Correct: re-runs only when id changes** + +```tsx +useEffect(() => { + console.log(user.id) +}, [user.id]) +``` + +**For derived state, compute outside effect:** + +```tsx +// Incorrect: runs on width=767, 766, 765... +useEffect(() => { + if (width < 768) { + enableMobileMode() + } +}, [width]) + +// Correct: runs only on boolean transition +const isMobile = width < 768 +useEffect(() => { + if (isMobile) { + enableMobileMode() + } +}, [isMobile]) +``` + +### 5.8 Put Interaction Logic in Event Handlers + +**Impact: MEDIUM (avoids effect re-runs and duplicate side effects)** + +If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action. + +**Incorrect: event modeled as state + effect** + +```tsx +function Form() { + const [submitted, setSubmitted] = useState(false) + const theme = useContext(ThemeContext) + + useEffect(() => { + if (submitted) { + post('/api/register') + showToast('Registered', theme) + } + }, [submitted, theme]) + + return +} +``` + +**Correct: do it in the handler** + +```tsx +function Form() { + const theme = useContext(ThemeContext) + + function handleSubmit() { + post('/api/register') + showToast('Registered', theme) + } + + return +} +``` + +Reference: [https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler) + +### 5.9 Split Combined Hook Computations + +**Impact: MEDIUM (avoids recomputing independent steps)** + +When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value. + +**Incorrect: changing `sortOrder` recomputes filtering** + +```tsx +const sortedProducts = useMemo(() => { + const filtered = products.filter((p) => p.category === category) + const sorted = filtered.toSorted((a, b) => + sortOrder === "asc" ? a.price - b.price : b.price - a.price + ) + return sorted +}, [products, category, sortOrder]) +``` + +**Correct: filtering only recomputes when products or category change** + +```tsx +const filteredProducts = useMemo( + () => products.filter((p) => p.category === category), + [products, category] +) + +const sortedProducts = useMemo( + () => + filteredProducts.toSorted((a, b) => + sortOrder === "asc" ? a.price - b.price : b.price - a.price + ), + [filteredProducts, sortOrder] +) +``` + +This pattern also applies to `useEffect` when combining unrelated side effects: + +**Incorrect: both effects run when either dependency changes** + +```tsx +useEffect(() => { + analytics.trackPageView(pathname) + document.title = `${pageTitle} | My App` +}, [pathname, pageTitle]) +``` + +**Correct: effects run independently** + +```tsx +useEffect(() => { + analytics.trackPageView(pathname) +}, [pathname]) + +useEffect(() => { + document.title = `${pageTitle} | My App` +}, [pageTitle]) +``` + +**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you. + +### 5.10 Subscribe to Derived State + +**Impact: MEDIUM (reduces re-render frequency)** + +Subscribe to derived boolean state instead of continuous values to reduce re-render frequency. + +**Incorrect: re-renders on every pixel change** + +```tsx +function Sidebar() { + const width = useWindowWidth() // updates continuously + const isMobile = width < 768 + return