[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,91 +2,202 @@
id: wiki-2026-0508-spa-single-page-application
title: SPA (Single Page Application)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [single-page-app, client-side-routing-app]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [frontend, spa, react, vue, routing, architecture]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: react-vue-svelte
---
# [[SPA (Single Page Application)|SPA (Single Page Application]]
# SPA (Single Page Application)
## 📌 한 줄 통찰 (The Karpathy Summary)
SPA(Single Page Application)는 주로 클라이언트 측 렌더링(CSR) 방식을 사용하여 구축되는 웹 애플리케이션 형태입니다 [1, 2]. 초기 로드 시 서버로부터 전체 페이지를 받아오는 대신 최소한의 뼈대만 포함된 단일 HTML을 로드하고, 이후에는 [[JavaScript|JavaScript]]를 이용해 브라우저 내에서 동적으로 콘텐츠와 라우팅을 생성합니다 [2, 3]. 이를 통해 매번 페이지를 새로고침할 필요 없이 부드럽고 '앱과 같은(app-like)' 사용자 경험을 제공하는 것이 특징입니다 [4, 5].
## 한 줄
> **"매 single HTML shell 의 의 client-side routing + dynamic rendering 의 driven 의 web app 의 architecture."**. 매 2010s 의 의 dominant pattern (AngularJS, Backbone, Ember → React, Vue, Angular), 매 2026 의 RSC / SSR / Islands 의 ascendency 의 의 SPA 의 niche 화 — 매 highly-interactive dashboards, internal tools, complex stateful UIs 의 의 the right tool 이며 marketing/content 의 의 의 SSG/SSR 의 권장.
## 📖 구조화된 지식 (Synthesized Content)
- **렌더링 방식 및 작동 원리:** SPA는 클라이언트 측 렌더링(CSR) 환경과 뗄 수 없는 관계를 갖습니다 [1, 2]. 사용자가 SPA에 접속하면 브라우저는 헤더, 푸터, 내비게이션 바 등 반복되는 요소가 포함된 뼈대 수준의 최소 HTML과 JavaScript 번들을 다운로드합니다 [2, 3, 5, 6]. 초기 로드 이후에는 서버로부터 새로운 전체 페이지를 요청하지 않으며, JavaScript가 데이터를 동적으로 가져와 브라우저 내에서 인터페이스를 직접 구축하고 경로(Route)를 생성합니다 [3, 5, 6].
- **성능적 이점 및 장점:** 전체 페이지를 다시 로드할 때 발생하는 끊김 현상을 없애고, 필요한 데이터만 서버에서 받아 현재 페이지를 동적으로 덮어쓰기 때문에 매우 유동적이고 즉각적인 반응성을 제공합니다 [5, 7]. 또한, HTML, CSS, JavaScript 파일만 서비스할 수 있는 정적 서버만으로도 호스팅이 가능하여 고비용의 서버 인프라에 대한 의존도 및 호스팅 비용을 크게 줄일 수 있습니다 [8].
- **한계점 및 단점:** 사용자가 첫 화면을 보기 전에 브라우저가 모든 JavaScript 코드를 다운로드하고 파싱 및 실행해야 하므로 초기 로딩 속도(First Contentful Paint)가 상대적으로 느립니다 [4, 9, 10]. 또한 처음 서버에서 제공하는 HTML이 거의 비어 있기 때문에, JavaScript를 원활하게 실행하지 못하는 검색 엔진 크롤러에게는 콘텐츠가 보이지 않아 검색 엔진 최적화(SEO) 측면에서 한계가 있습니다 [4, 9, 11, 12].
- **주요 사용 사례:** SEO가 최우선 고려 사항이 아니고 풍부한 상호작용과 실시간 데이터 업데이트가 중요한 환경에 가장 적합합니다 [13, 14]. 주로 로그인 장벽 뒤에 있는 사용자 대시보드, 내부 비즈니스 도구, [[SaaS|SaaS]](Software as a Service) 플랫폼 등의 구축에 활용되며, React, Vue.js, Angular와 같은 최신 프레임워크가 SPA 구축에 널리 사용됩니다 [6, 13-16].
## 매 핵심
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Client-Side Rendering (CSR)|Client-Side Rendering (CSR]], First Contentful Paint (FCP), Search Engine Optimization (SEO, React, Document Object Model (DOM)
- **Projects/Contexts:** SaaS 플랫폼, 사용자 대시보드, 내부 비즈니스 도구
- **Contradictions/Notes:** 소스는 SPA 및 CSR 방식이 상호작용성이 뛰어난 데 반해 SEO와 초기 로딩 속도에 약점을 가지고 있다고 지적합니다. 따라서 검색 노출이 중요한 마케팅 페이지나 블로그, 전자상거래 사이트 등에서는 순수 SPA(CSR) 대신 SSR(Server-Side Rendering)이나 SSG(Static Site Generation) 방식을 적용하거나 혼합(Hybrid)하여 사용하는 것이 권장됩니다 [11, 13, 17, 18].
### 매 정의
- 1 HTML document 의 load — subsequent navigation 의 JS 의 driven (no full page reload).
- Client-side router 의 URL ↔ component tree 의 mapping.
- Data 의 fetch via XHR/Fetch — JSON API or RPC.
- State 의 client 의 in-memory (Redux, Zustand, Jotai, TanStack Query).
---
*Last updated: 2026-04-25*
### 매 trade-offs
- **Pros**: snappy in-app navigation, rich interactivity, app-like UX, shared state across views.
- **Cons**: SEO 의 weak (without SSR), initial bundle 의 large, white screen 의 risk, accessibility 의 careful 의 wiring.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 vs. modern alternatives
- **SSR / SSG (Next.js, Remix)**: server 의 HTML 의 generate, hydration 의 client interactivity 의 add.
- **RSC (React Server Components, 2026 mainstream)**: server-only components + client islands.
- **Islands (Astro, Fresh, 11ty)**: static HTML + targeted hydration 의 islands.
- **MPA (Multi-Page App)**: traditional server-rendered pages — Hotwire / Inertia 의 의 modern revival.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. Internal admin dashboards (high interactivity, no SEO need).
2. Authenticated SaaS apps (Linear, Figma, Notion).
3. Real-time collaboration (CRDT-driven, websocket-heavy).
4. Browser-based tools (Excalidraw, Tldraw).
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### React Router (data router, 2026)
```tsx
import { createBrowserRouter, RouterProvider } from 'react-router';
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
const router = createBrowserRouter([
{
path: '/',
Component: Layout,
children: [
{ index: true, Component: Home },
{ path: 'projects/:id', Component: Project, loader: projectLoader },
{ path: '*', Component: NotFound },
],
},
]);
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
export const App = () => <RouterProvider router={router} />;
```
## 🤔 의사결정 기준 (Decision Criteria)
### Data fetching (TanStack Query)
```tsx
import { useQuery } from '@tanstack/react-query';
**선택 A를 써야 할 때:**
- *(TODO)*
export function ProjectView({ id }: { id: string }) {
const { data, isPending, error } = useQuery({
queryKey: ['project', id],
queryFn: () => fetch(`/api/projects/${id}`).then((r) => r.json()),
staleTime: 60_000,
});
if (isPending) return <Skeleton />;
if (error) return <ErrorBoundary error={error} />;
return <ProjectDetail project={data} />;
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Client state (Zustand)
```ts
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
**기본값:**
> *(TODO)*
export const useUIStore = create(
persist<{ sidebar: boolean; toggle: () => void }>(
(set) => ({
sidebar: true,
toggle: () => set((s) => ({ sidebar: !s.sidebar })),
}),
{ name: 'ui-store' },
),
);
```
## ❌ 안티패턴 (Anti-Patterns)
### Code splitting (lazy routes)
```tsx
import { lazy, Suspense } from 'react';
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
const Settings = lazy(() => import('./routes/Settings'));
const router = createBrowserRouter([
{
path: '/settings',
element: (
<Suspense fallback={<RouteSkeleton />}>
<Settings />
</Suspense>
),
},
]);
```
### History API (without router)
```ts
window.history.pushState({}, '', '/projects/42');
window.dispatchEvent(new PopStateEvent('popstate'));
window.addEventListener('popstate', () => {
render(parseRoute(location.pathname));
});
```
### Auth guard (route loader)
```tsx
async function projectLoader({ params }: LoaderFunctionArgs) {
const session = await getSession();
if (!session) throw redirect('/login');
return fetch(`/api/projects/${params.id}`).then((r) => r.json());
}
```
### Vite SPA의 setup
```ts
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
build: { sourcemap: true, target: 'es2022' },
server: { historyApiFallback: true },
});
```
### SEO 의 fallback (prerender + hydrate)
```ts
// vite-plugin-prerender
import prerender from 'vite-plugin-prerender';
export default {
plugins: [
react(),
prerender({ routes: ['/', '/about', '/pricing'] }),
],
};
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Marketing site, blog | **SSG** (Astro, Next.js static, 11ty) |
| Content site with personalization | **SSR** (Next.js, Remix) |
| Dashboards, admin tools | **SPA** (React Router + Vite) |
| Highly interactive editor | **SPA** with code-splitting |
| Public app needing SEO + interactivity | **Next.js (RSC + client islands)** |
| MPA-style with sprinkles | **Hotwire / Inertia.js** |
**기본값**: 2026 의 default 는 **Next.js / Remix (SSR + RSC)** — pure SPA 는 internal tools / authenticated apps 의 으로 의 reserve.
## 🔗 Graph
- 부모: [[Web-Application-Architecture]] · [[Frontend-Architecture]]
- 변형: [[SSR]] · [[SSG]] · [[Islands-Architecture]] · [[React-Server-Components]]
- 응용: [[Admin-Dashboard]] · [[SaaS-Frontend]] · [[Realtime-Collaboration-UI]]
- Adjacent: [[React-Router]] · [[TanStack-Query]] · [[Vite]] · [[Code-Splitting]]
## 🤖 LLM 활용
**언제**: highly-interactive authenticated app, no SEO requirement, complex client state, real-time collaboration.
**언제 X**: marketing/content site (SSG), public SEO-critical content (SSR/RSC), simple form-driven app (MPA).
## 안티패턴
- **SPA 의 marketing site**: SEO 의 weak, LCP 의 poor — SSG 의 사용.
- **Bundle 의 single chunk**: route-based code splitting 의 default.
- **Auth state 의 localStorage 의 raw token**: HttpOnly cookie + refresh flow 의 사용.
- **Client routing 의 server fallback 없음**: 404 의 deep link 의 — `historyApiFallback` / catch-all rewrite.
- **No skeleton / suspense**: white screen on slow data — Suspense + skeletons.
- **Global state 의 overuse**: server state 의 TanStack Query, UI state 의 Zustand/Jotai 의 separate.
## 🧪 검증 / 중복
- Verified (React Router 7 docs, Vue Router 4, MDN SPA architecture, web.dev rendering patterns 2026).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full SPA architecture with 2026 trade-offs vs RSC/Islands |