Commit 4489f507 authored by Lê Bảo Hồng Đức's avatar Lê Bảo Hồng Đức

fix

parent 138856d6
# React Composition Patterns
**Version 1.0.0**
Engineering
January 2026
> **Note:**
> This document is mainly for agents and LLMs to follow when maintaining,
> generating, or refactoring React codebases using composition. Humans
> may also find it useful, but guidance here is optimized for automation
> and consistency by AI-assisted workflows.
---
## Abstract
Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.
---
## Table of Contents
1. [Component Architecture](#1-component-architecture)**HIGH**
- 1.1 [Avoid Boolean Prop Proliferation](#11-avoid-boolean-prop-proliferation)
- 1.2 [Use Compound Components](#12-use-compound-components)
2. [State Management](#2-state-management)**MEDIUM**
- 2.1 [Decouple State Management from UI](#21-decouple-state-management-from-ui)
- 2.2 [Define Generic Context Interfaces for Dependency Injection](#22-define-generic-context-interfaces-for-dependency-injection)
- 2.3 [Lift State into Provider Components](#23-lift-state-into-provider-components)
3. [Implementation Patterns](#3-implementation-patterns)**MEDIUM**
- 3.1 [Create Explicit Component Variants](#31-create-explicit-component-variants)
- 3.2 [Prefer Composing Children Over Render Props](#32-prefer-composing-children-over-render-props)
4. [React 19 APIs](#4-react-19-apis)**MEDIUM**
- 4.1 [React 19 API Changes](#41-react-19-api-changes)
---
## 1. Component Architecture
**Impact: HIGH**
Fundamental patterns for structuring components to avoid prop
proliferation and enable flexible composition.
### 1.1 Avoid Boolean Prop Proliferation
**Impact: CRITICAL (prevents unmaintainable component variants)**
Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize
component behavior. Each boolean doubles possible states and creates
unmaintainable conditional logic. Use composition instead.
**Incorrect: boolean props create exponential complexity**
```tsx
function Composer({
onSubmit,
isThread,
channelId,
isDMThread,
dmId,
isEditing,
isForwarding,
}: Props) {
return (
<form>
<Header />
<Input />
{isDMThread ? (
<AlsoSendToDMField id={dmId} />
) : isThread ? (
<AlsoSendToChannelField id={channelId} />
) : null}
{isEditing ? (
<EditActions />
) : isForwarding ? (
<ForwardActions />
) : (
<DefaultActions />
)}
<Footer onSubmit={onSubmit} />
</form>
)
}
```
**Correct: composition eliminates conditionals**
```tsx
// Channel composer
function ChannelComposer() {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Attachments />
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Thread composer - adds "also send to channel" field
function ThreadComposer({ channelId }: { channelId: string }) {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<AlsoSendToChannelField id={channelId} />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Edit composer - different footer actions
function EditComposer() {
return (
<Composer.Frame>
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.CancelEdit />
<Composer.SaveEdit />
</Composer.Footer>
</Composer.Frame>
)
}
```
Each variant is explicit about what it renders. We can share internals without
sharing a single monolithic parent.
### 1.2 Use Compound Components
**Impact: HIGH (enables flexible composition without prop drilling)**
Structure complex components as compound components with a shared context. Each
subcomponent accesses shared state via context, not props. Consumers compose the
pieces they need.
**Incorrect: monolithic component with render props**
```tsx
function Composer({
renderHeader,
renderFooter,
renderActions,
showAttachments,
showFormatting,
showEmojis,
}: Props) {
return (
<form>
{renderHeader?.()}
<Input />
{showAttachments && <Attachments />}
{renderFooter ? (
renderFooter()
) : (
<Footer>
{showFormatting && <Formatting />}
{showEmojis && <Emojis />}
{renderActions?.()}
</Footer>
)}
</form>
)
}
```
**Correct: compound components with shared context**
```tsx
const ComposerContext = createContext<ComposerContextValue | null>(null)
function ComposerProvider({ children, state, actions, meta }: ProviderProps) {
return (
<ComposerContext value={{ state, actions, meta }}>
{children}
</ComposerContext>
)
}
function ComposerFrame({ children }: { children: React.ReactNode }) {
return <form>{children}</form>
}
function ComposerInput() {
const {
state,
actions: { update },
meta: { inputRef },
} = use(ComposerContext)
return (
<TextInput
ref={inputRef}
value={state.input}
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
/>
)
}
function ComposerSubmit() {
const {
actions: { submit },
} = use(ComposerContext)
return <Button onPress={submit}>Send</Button>
}
// Export as compound component
const Composer = {
Provider: ComposerProvider,
Frame: ComposerFrame,
Input: ComposerInput,
Submit: ComposerSubmit,
Header: ComposerHeader,
Footer: ComposerFooter,
Attachments: ComposerAttachments,
Formatting: ComposerFormatting,
Emojis: ComposerEmojis,
}
```
**Usage:**
```tsx
<Composer.Provider state={state} actions={actions} meta={meta}>
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
</Composer.Provider>
```
Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.
---
## 2. State Management
**Impact: MEDIUM**
Patterns for lifting state and managing shared context across
composed components.
### 2.1 Decouple State Management from UI
**Impact: MEDIUM (enables swapping state implementations without changing UI)**
The provider component should be the only place that knows how state is managed.
UI components consume the context interface—they don't know if state comes from
useState, Zustand, or a server sync.
**Incorrect: UI coupled to state implementation**
```tsx
function ChannelComposer({ channelId }: { channelId: string }) {
// UI component knows about global state implementation
const state = useGlobalChannelState(channelId)
const { submit, updateInput } = useChannelSync(channelId)
return (
<Composer.Frame>
<Composer.Input
value={state.input}
onChange={(text) => sync.updateInput(text)}
/>
<Composer.Submit onPress={() => sync.submit()} />
</Composer.Frame>
)
}
```
**Correct: state management isolated in provider**
```tsx
// Provider handles all state management details
function ChannelProvider({
channelId,
children,
}: {
channelId: string
children: React.ReactNode
}) {
const { state, update, submit } = useGlobalChannel(channelId)
const inputRef = useRef(null)
return (
<Composer.Provider
state={state}
actions={{ update, submit }}
meta={{ inputRef }}
>
{children}
</Composer.Provider>
)
}
// UI component only knows about the context interface
function ChannelComposer() {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Usage
function Channel({ channelId }: { channelId: string }) {
return (
<ChannelProvider channelId={channelId}>
<ChannelComposer />
</ChannelProvider>
)
}
```
**Different providers, same UI:**
```tsx
// Local state for ephemeral forms
function ForwardMessageProvider({ children }) {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
return (
<Composer.Provider
state={state}
actions={{ update: setState, submit: forwardMessage }}
>
{children}
</Composer.Provider>
)
}
// Global synced state for channels
function ChannelProvider({ channelId, children }) {
const { state, update, submit } = useGlobalChannel(channelId)
return (
<Composer.Provider state={state} actions={{ update, submit }}>
{children}
</Composer.Provider>
)
}
```
The same `Composer.Input` component works with both providers because it only
depends on the context interface, not the implementation.
### 2.2 Define Generic Context Interfaces for Dependency Injection
**Impact: HIGH (enables dependency-injectable state across use-cases)**
Define a **generic interface** for your component context with three parts:
`state`, `actions`, and `meta`. This interface is a contract that any provider
can implement—enabling the same UI components to work with completely different
state implementations.
**Core principle:** Lift state, compose internals, make state
dependency-injectable.
**Incorrect: UI coupled to specific state implementation**
```tsx
function ComposerInput() {
// Tightly coupled to a specific hook
const { input, setInput } = useChannelComposerState()
return <TextInput value={input} onChangeText={setInput} />
}
```
**Correct: generic interface enables dependency injection**
```tsx
// Define a GENERIC interface that any provider can implement
interface ComposerState {
input: string
attachments: Attachment[]
isSubmitting: boolean
}
interface ComposerActions {
update: (updater: (state: ComposerState) => ComposerState) => void
submit: () => void
}
interface ComposerMeta {
inputRef: React.RefObject<TextInput>
}
interface ComposerContextValue {
state: ComposerState
actions: ComposerActions
meta: ComposerMeta
}
const ComposerContext = createContext<ComposerContextValue | null>(null)
```
**UI components consume the interface, not the implementation:**
```tsx
function ComposerInput() {
const {
state,
actions: { update },
meta,
} = use(ComposerContext)
// This component works with ANY provider that implements the interface
return (
<TextInput
ref={meta.inputRef}
value={state.input}
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
/>
)
}
```
**Different providers implement the same interface:**
```tsx
// Provider A: Local state for ephemeral forms
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState(initialState)
const inputRef = useRef(null)
const submit = useForwardMessage()
return (
<ComposerContext
value={{
state,
actions: { update: setState, submit },
meta: { inputRef },
}}
>
{children}
</ComposerContext>
)
}
// Provider B: Global synced state for channels
function ChannelProvider({ channelId, children }: Props) {
const { state, update, submit } = useGlobalChannel(channelId)
const inputRef = useRef(null)
return (
<ComposerContext
value={{
state,
actions: { update, submit },
meta: { inputRef },
}}
>
{children}
</ComposerContext>
)
}
```
**The same composed UI works with both:**
```tsx
// Works with ForwardMessageProvider (local state)
<ForwardMessageProvider>
<Composer.Frame>
<Composer.Input />
<Composer.Submit />
</Composer.Frame>
</ForwardMessageProvider>
// Works with ChannelProvider (global synced state)
<ChannelProvider channelId="abc">
<Composer.Frame>
<Composer.Input />
<Composer.Submit />
</Composer.Frame>
</ChannelProvider>
```
**Custom UI outside the component can access state and actions:**
```tsx
function ForwardMessageDialog() {
return (
<ForwardMessageProvider>
<Dialog>
{/* The composer UI */}
<Composer.Frame>
<Composer.Input placeholder="Add a message, if you'd like." />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
</Composer.Footer>
</Composer.Frame>
{/* Custom UI OUTSIDE the composer, but INSIDE the provider */}
<MessagePreview />
{/* Actions at the bottom of the dialog */}
<DialogActions>
<CancelButton />
<ForwardButton />
</DialogActions>
</Dialog>
</ForwardMessageProvider>
)
}
// This button lives OUTSIDE Composer.Frame but can still submit based on its context!
function ForwardButton() {
const {
actions: { submit },
} = use(ComposerContext)
return <Button onPress={submit}>Forward</Button>
}
// This preview lives OUTSIDE Composer.Frame but can read composer's state!
function MessagePreview() {
const { state } = use(ComposerContext)
return <Preview message={state.input} attachments={state.attachments} />
}
```
The provider boundary is what matters—not the visual nesting. Components that
need shared state don't have to be inside the `Composer.Frame`. They just need
to be within the provider.
The `ForwardButton` and `MessagePreview` are not visually inside the composer
box, but they can still access its state and actions. This is the power of
lifting state into providers.
The UI is reusable bits you compose together. The state is dependency-injected
by the provider. Swap the provider, keep the UI.
### 2.3 Lift State into Provider Components
**Impact: HIGH (enables state sharing outside component boundaries)**
Move state management into dedicated provider components. This allows sibling
components outside the main UI to access and modify state without prop drilling
or awkward refs.
**Incorrect: state trapped inside component**
```tsx
function ForwardMessageComposer() {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
return (
<Composer.Frame>
<Composer.Input />
<Composer.Footer />
</Composer.Frame>
)
}
// Problem: How does this button access composer state?
function ForwardMessageDialog() {
return (
<Dialog>
<ForwardMessageComposer />
<MessagePreview /> {/* Needs composer state */}
<DialogActions>
<CancelButton />
<ForwardButton /> {/* Needs to call submit */}
</DialogActions>
</Dialog>
)
}
```
**Incorrect: useEffect to sync state up**
```tsx
function ForwardMessageDialog() {
const [input, setInput] = useState('')
return (
<Dialog>
<ForwardMessageComposer onInputChange={setInput} />
<MessagePreview input={input} />
</Dialog>
)
}
function ForwardMessageComposer({ onInputChange }) {
const [state, setState] = useState(initialState)
useEffect(() => {
onInputChange(state.input) // Sync on every change 😬
}, [state.input])
}
```
**Incorrect: reading state from ref on submit**
```tsx
function ForwardMessageDialog() {
const stateRef = useRef(null)
return (
<Dialog>
<ForwardMessageComposer stateRef={stateRef} />
<ForwardButton onPress={() => submit(stateRef.current)} />
</Dialog>
)
}
```
**Correct: state lifted to provider**
```tsx
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
const inputRef = useRef(null)
return (
<Composer.Provider
state={state}
actions={{ update: setState, submit: forwardMessage }}
meta={{ inputRef }}
>
{children}
</Composer.Provider>
)
}
function ForwardMessageDialog() {
return (
<ForwardMessageProvider>
<Dialog>
<ForwardMessageComposer />
<MessagePreview /> {/* Custom components can access state and actions */}
<DialogActions>
<CancelButton />
<ForwardButton /> {/* Custom components can access state and actions */}
</DialogActions>
</Dialog>
</ForwardMessageProvider>
)
}
function ForwardButton() {
const { actions } = use(Composer.Context)
return <Button onPress={actions.submit}>Forward</Button>
}
```
The ForwardButton lives outside the Composer.Frame but still has access to the
submit action because it's within the provider. Even though it's a one-off
component, it can still access the composer's state and actions from outside the
UI itself.
**Key insight:** Components that need shared state don't have to be visually
nested inside each other—they just need to be within the same provider.
---
## 3. Implementation Patterns
**Impact: MEDIUM**
Specific techniques for implementing compound components and
context providers.
### 3.1 Create Explicit Component Variants
**Impact: MEDIUM (self-documenting code, no hidden conditionals)**
Instead of one component with many boolean props, create explicit variant
components. Each variant composes the pieces it needs. The code documents
itself.
**Incorrect: one component, many modes**
```tsx
// What does this component actually render?
<Composer
isThread
isEditing={false}
channelId='abc'
showAttachments
showFormatting={false}
/>
```
**Correct: explicit variants**
```tsx
// Immediately clear what this renders
<ThreadComposer channelId="abc" />
// Or
<EditMessageComposer messageId="xyz" />
// Or
<ForwardMessageComposer messageId="123" />
```
Each implementation is unique, explicit and self-contained. Yet they can each
use shared parts.
**Implementation:**
```tsx
function ThreadComposer({ channelId }: { channelId: string }) {
return (
<ThreadProvider channelId={channelId}>
<Composer.Frame>
<Composer.Input />
<AlsoSendToChannelField channelId={channelId} />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
</ThreadProvider>
)
}
function EditMessageComposer({ messageId }: { messageId: string }) {
return (
<EditMessageProvider messageId={messageId}>
<Composer.Frame>
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.CancelEdit />
<Composer.SaveEdit />
</Composer.Footer>
</Composer.Frame>
</EditMessageProvider>
)
}
function ForwardMessageComposer({ messageId }: { messageId: string }) {
return (
<ForwardMessageProvider messageId={messageId}>
<Composer.Frame>
<Composer.Input placeholder="Add a message, if you'd like." />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Mentions />
</Composer.Footer>
</Composer.Frame>
</ForwardMessageProvider>
)
}
```
Each variant is explicit about:
- What provider/state it uses
- What UI elements it includes
- What actions are available
No boolean prop combinations to reason about. No impossible states.
### 3.2 Prefer Composing Children Over Render Props
**Impact: MEDIUM (cleaner composition, better readability)**
Use `children` for composition instead of `renderX` props. Children are more
readable, compose naturally, and don't require understanding callback
signatures.
**Incorrect: render props**
```tsx
function Composer({
renderHeader,
renderFooter,
renderActions,
}: {
renderHeader?: () => React.ReactNode
renderFooter?: () => React.ReactNode
renderActions?: () => React.ReactNode
}) {
return (
<form>
{renderHeader?.()}
<Input />
{renderFooter ? renderFooter() : <DefaultFooter />}
{renderActions?.()}
</form>
)
}
// Usage is awkward and inflexible
return (
<Composer
renderHeader={() => <CustomHeader />}
renderFooter={() => (
<>
<Formatting />
<Emojis />
</>
)}
renderActions={() => <SubmitButton />}
/>
)
```
**Correct: compound components with children**
```tsx
function ComposerFrame({ children }: { children: React.ReactNode }) {
return <form>{children}</form>
}
function ComposerFooter({ children }: { children: React.ReactNode }) {
return <footer className='flex'>{children}</footer>
}
// Usage is flexible
return (
<Composer.Frame>
<CustomHeader />
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<SubmitButton />
</Composer.Footer>
</Composer.Frame>
)
```
**When render props are appropriate:**
```tsx
// Render props work well when you need to pass data back
<List
data={items}
renderItem={({ item, index }) => <Item item={item} index={index} />}
/>
```
Use render props when the parent needs to provide data or state to the child.
Use children when composing static structure.
---
## 4. React 19 APIs
**Impact: MEDIUM**
React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.
### 4.1 React 19 API Changes
**Impact: MEDIUM (cleaner component definitions and context usage)**
> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.
In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.
**Incorrect: forwardRef in React 19**
```tsx
const ComposerInput = forwardRef<TextInput, Props>((props, ref) => {
return <TextInput ref={ref} {...props} />
})
```
**Correct: ref as a regular prop**
```tsx
function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref<TextInput> }) {
return <TextInput ref={ref} {...props} />
}
```
**Incorrect: useContext in React 19**
```tsx
const value = useContext(MyContext)
```
**Correct: use instead of useContext**
```tsx
const value = use(MyContext)
```
`use()` can also be called conditionally, unlike `useContext()`.
---
## References
1. [https://react.dev](https://react.dev)
2. [https://react.dev/learn/passing-data-deeply-with-context](https://react.dev/learn/passing-data-deeply-with-context)
3. [https://react.dev/reference/react/use](https://react.dev/reference/react/use)
# React Composition Patterns
A structured repository for React composition patterns that scale. These
patterns help avoid boolean prop proliferation by using compound components,
lifting state, and composing internals.
## Structure
- `rules/` - Individual rule files (one per rule)
- `_sections.md` - Section metadata (titles, impacts, descriptions)
- `_template.md` - Template for creating new rules
- `area-description.md` - Individual rule files
- `metadata.json` - Document metadata (version, organization, abstract)
- **`AGENTS.md`** - Compiled output (generated)
## Rules
### Component Architecture (CRITICAL)
- `architecture-avoid-boolean-props.md` - Don't add boolean props to customize
behavior
- `architecture-compound-components.md` - Structure as compound components with
shared context
### State Management (HIGH)
- `state-lift-state.md` - Lift state into provider components
- `state-context-interface.md` - Define clear context interfaces
(state/actions/meta)
- `state-decouple-implementation.md` - Decouple state management from UI
### Implementation Patterns (MEDIUM)
- `patterns-children-over-render-props.md` - Prefer children over renderX props
- `patterns-explicit-variants.md` - Create explicit component variants
## Core Principles
1. **Composition over configuration** — Instead of adding props, let consumers
compose
2. **Lift your state** — State in providers, not trapped in components
3. **Compose your internals** — Subcomponents access context, not props
4. **Explicit variants** — Create ThreadComposer, EditComposer, not Composer
with isThread
## Creating a New Rule
1. Copy `rules/_template.md` to `rules/area-description.md`
2. Choose the appropriate area prefix:
- `architecture-` for Component Architecture
- `state-` for State Management
- `patterns-` for Implementation Patterns
3. Fill in the frontmatter and content
4. Ensure you have clear examples with explanations
## Impact Levels
- `CRITICAL` - Foundational patterns, prevents unmaintainable code
- `HIGH` - Significant maintainability improvements
- `MEDIUM` - Good practices for cleaner code
---
name: vercel-composition-patterns
description:
React composition patterns that scale. Use when refactoring components with
boolean prop proliferation, building flexible component libraries, or
designing reusable APIs. Triggers on tasks involving compound components,
render props, context providers, or component architecture. Includes React 19
API changes.
license: MIT
metadata:
author: vercel
version: '1.0.0'
---
# React Composition Patterns
Composition patterns for building flexible, maintainable React components. Avoid
boolean prop proliferation by using compound components, lifting state, and
composing internals. These patterns make codebases easier for both humans and AI
agents to work with as they scale.
## When to Apply
Reference these guidelines when:
- Refactoring components with many boolean props
- Building reusable component libraries
- Designing flexible component APIs
- Reviewing component architecture
- Working with compound components or context providers
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
| -------- | ----------------------- | ------ | --------------- |
| 1 | Component Architecture | HIGH | `architecture-` |
| 2 | State Management | MEDIUM | `state-` |
| 3 | Implementation Patterns | MEDIUM | `patterns-` |
| 4 | React 19 APIs | MEDIUM | `react19-` |
## Quick Reference
### 1. Component Architecture (HIGH)
- `architecture-avoid-boolean-props` - Don't add boolean props to customize
behavior; use composition
- `architecture-compound-components` - Structure complex components with shared
context
### 2. State Management (MEDIUM)
- `state-decouple-implementation` - Provider is the only place that knows how
state is managed
- `state-context-interface` - Define generic interface with state, actions, meta
for dependency injection
- `state-lift-state` - Move state into provider components for sibling access
### 3. Implementation Patterns (MEDIUM)
- `patterns-explicit-variants` - Create explicit variant components instead of
boolean modes
- `patterns-children-over-render-props` - Use children for composition instead
of renderX props
### 4. React 19 APIs (MEDIUM)
> **⚠️ React 19+ only.** Skip this section if using React 18 or earlier.
- `react19-no-forwardref` - Don't use `forwardRef`; use `use()` instead of `useContext()`
## How to Use
Read individual rule files for detailed explanations and code examples:
```
rules/architecture-avoid-boolean-props.md
rules/state-context-interface.md
```
Each rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Additional context and references
## Full Compiled Document
For the complete guide with all rules expanded: `AGENTS.md`
{
"version": "1.0.0",
"organization": "Engineering",
"date": "January 2026",
"abstract": "Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.",
"references": [
"https://react.dev",
"https://react.dev/learn/passing-data-deeply-with-context",
"https://react.dev/reference/react/use"
]
}
# Sections
This file defines all sections, their ordering, impact levels, and descriptions.
The section ID (in parentheses) is the filename prefix used to group rules.
---
## 1. Component Architecture (architecture)
**Impact:** HIGH
**Description:** Fundamental patterns for structuring components to avoid prop
proliferation and enable flexible composition.
## 2. State Management (state)
**Impact:** MEDIUM
**Description:** Patterns for lifting state and managing shared context across
composed components.
## 3. Implementation Patterns (patterns)
**Impact:** MEDIUM
**Description:** Specific techniques for implementing compound components and
context providers.
## 4. React 19 APIs (react19)
**Impact:** MEDIUM
**Description:** React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.
---
title: Rule Title Here
impact: MEDIUM
impactDescription: brief description of impact
tags: composition, components
---
## Rule Title Here
Brief explanation of the rule and why it matters.
**Incorrect:**
```tsx
// Bad code example
```
**Correct:**
```tsx
// Good code example
```
Reference: [Link](https://example.com)
---
title: Avoid Boolean Prop Proliferation
impact: CRITICAL
impactDescription: prevents unmaintainable component variants
tags: composition, props, architecture
---
## Avoid Boolean Prop Proliferation
Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize
component behavior. Each boolean doubles possible states and creates
unmaintainable conditional logic. Use composition instead.
**Incorrect (boolean props create exponential complexity):**
```tsx
function Composer({
onSubmit,
isThread,
channelId,
isDMThread,
dmId,
isEditing,
isForwarding,
}: Props) {
return (
<form>
<Header />
<Input />
{isDMThread ? (
<AlsoSendToDMField id={dmId} />
) : isThread ? (
<AlsoSendToChannelField id={channelId} />
) : null}
{isEditing ? (
<EditActions />
) : isForwarding ? (
<ForwardActions />
) : (
<DefaultActions />
)}
<Footer onSubmit={onSubmit} />
</form>
)
}
```
**Correct (composition eliminates conditionals):**
```tsx
// Channel composer
function ChannelComposer() {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Attachments />
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Thread composer - adds "also send to channel" field
function ThreadComposer({ channelId }: { channelId: string }) {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<AlsoSendToChannelField id={channelId} />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Edit composer - different footer actions
function EditComposer() {
return (
<Composer.Frame>
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.CancelEdit />
<Composer.SaveEdit />
</Composer.Footer>
</Composer.Frame>
)
}
```
Each variant is explicit about what it renders. We can share internals without
sharing a single monolithic parent.
---
title: Use Compound Components
impact: HIGH
impactDescription: enables flexible composition without prop drilling
tags: composition, compound-components, architecture
---
## Use Compound Components
Structure complex components as compound components with a shared context. Each
subcomponent accesses shared state via context, not props. Consumers compose the
pieces they need.
**Incorrect (monolithic component with render props):**
```tsx
function Composer({
renderHeader,
renderFooter,
renderActions,
showAttachments,
showFormatting,
showEmojis,
}: Props) {
return (
<form>
{renderHeader?.()}
<Input />
{showAttachments && <Attachments />}
{renderFooter ? (
renderFooter()
) : (
<Footer>
{showFormatting && <Formatting />}
{showEmojis && <Emojis />}
{renderActions?.()}
</Footer>
)}
</form>
)
}
```
**Correct (compound components with shared context):**
```tsx
const ComposerContext = createContext<ComposerContextValue | null>(null)
function ComposerProvider({ children, state, actions, meta }: ProviderProps) {
return (
<ComposerContext value={{ state, actions, meta }}>
{children}
</ComposerContext>
)
}
function ComposerFrame({ children }: { children: React.ReactNode }) {
return <form>{children}</form>
}
function ComposerInput() {
const {
state,
actions: { update },
meta: { inputRef },
} = use(ComposerContext)
return (
<TextInput
ref={inputRef}
value={state.input}
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
/>
)
}
function ComposerSubmit() {
const {
actions: { submit },
} = use(ComposerContext)
return <Button onPress={submit}>Send</Button>
}
// Export as compound component
const Composer = {
Provider: ComposerProvider,
Frame: ComposerFrame,
Input: ComposerInput,
Submit: ComposerSubmit,
Header: ComposerHeader,
Footer: ComposerFooter,
Attachments: ComposerAttachments,
Formatting: ComposerFormatting,
Emojis: ComposerEmojis,
}
```
**Usage:**
```tsx
<Composer.Provider state={state} actions={actions} meta={meta}>
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
</Composer.Provider>
```
Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.
---
title: Prefer Composing Children Over Render Props
impact: MEDIUM
impactDescription: cleaner composition, better readability
tags: composition, children, render-props
---
## Prefer Children Over Render Props
Use `children` for composition instead of `renderX` props. Children are more
readable, compose naturally, and don't require understanding callback
signatures.
**Incorrect (render props):**
```tsx
function Composer({
renderHeader,
renderFooter,
renderActions,
}: {
renderHeader?: () => React.ReactNode
renderFooter?: () => React.ReactNode
renderActions?: () => React.ReactNode
}) {
return (
<form>
{renderHeader?.()}
<Input />
{renderFooter ? renderFooter() : <DefaultFooter />}
{renderActions?.()}
</form>
)
}
// Usage is awkward and inflexible
return (
<Composer
renderHeader={() => <CustomHeader />}
renderFooter={() => (
<>
<Formatting />
<Emojis />
</>
)}
renderActions={() => <SubmitButton />}
/>
)
```
**Correct (compound components with children):**
```tsx
function ComposerFrame({ children }: { children: React.ReactNode }) {
return <form>{children}</form>
}
function ComposerFooter({ children }: { children: React.ReactNode }) {
return <footer className='flex'>{children}</footer>
}
// Usage is flexible
return (
<Composer.Frame>
<CustomHeader />
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<SubmitButton />
</Composer.Footer>
</Composer.Frame>
)
```
**When render props are appropriate:**
```tsx
// Render props work well when you need to pass data back
<List
data={items}
renderItem={({ item, index }) => <Item item={item} index={index} />}
/>
```
Use render props when the parent needs to provide data or state to the child.
Use children when composing static structure.
---
title: Create Explicit Component Variants
impact: MEDIUM
impactDescription: self-documenting code, no hidden conditionals
tags: composition, variants, architecture
---
## Create Explicit Component Variants
Instead of one component with many boolean props, create explicit variant
components. Each variant composes the pieces it needs. The code documents
itself.
**Incorrect (one component, many modes):**
```tsx
// What does this component actually render?
<Composer
isThread
isEditing={false}
channelId='abc'
showAttachments
showFormatting={false}
/>
```
**Correct (explicit variants):**
```tsx
// Immediately clear what this renders
<ThreadComposer channelId="abc" />
// Or
<EditMessageComposer messageId="xyz" />
// Or
<ForwardMessageComposer messageId="123" />
```
Each implementation is unique, explicit and self-contained. Yet they can each
use shared parts.
**Implementation:**
```tsx
function ThreadComposer({ channelId }: { channelId: string }) {
return (
<ThreadProvider channelId={channelId}>
<Composer.Frame>
<Composer.Input />
<AlsoSendToChannelField channelId={channelId} />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
</ThreadProvider>
)
}
function EditMessageComposer({ messageId }: { messageId: string }) {
return (
<EditMessageProvider messageId={messageId}>
<Composer.Frame>
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.CancelEdit />
<Composer.SaveEdit />
</Composer.Footer>
</Composer.Frame>
</EditMessageProvider>
)
}
function ForwardMessageComposer({ messageId }: { messageId: string }) {
return (
<ForwardMessageProvider messageId={messageId}>
<Composer.Frame>
<Composer.Input placeholder="Add a message, if you'd like." />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Mentions />
</Composer.Footer>
</Composer.Frame>
</ForwardMessageProvider>
)
}
```
Each variant is explicit about:
- What provider/state it uses
- What UI elements it includes
- What actions are available
No boolean prop combinations to reason about. No impossible states.
---
title: React 19 API Changes
impact: MEDIUM
impactDescription: cleaner component definitions and context usage
tags: react19, refs, context, hooks
---
## React 19 API Changes
> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.
In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.
**Incorrect (forwardRef in React 19):**
```tsx
const ComposerInput = forwardRef<TextInput, Props>((props, ref) => {
return <TextInput ref={ref} {...props} />
})
```
**Correct (ref as a regular prop):**
```tsx
function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref<TextInput> }) {
return <TextInput ref={ref} {...props} />
}
```
**Incorrect (useContext in React 19):**
```tsx
const value = useContext(MyContext)
```
**Correct (use instead of useContext):**
```tsx
const value = use(MyContext)
```
`use()` can also be called conditionally, unlike `useContext()`.
---
title: Define Generic Context Interfaces for Dependency Injection
impact: HIGH
impactDescription: enables dependency-injectable state across use-cases
tags: composition, context, state, typescript, dependency-injection
---
## Define Generic Context Interfaces for Dependency Injection
Define a **generic interface** for your component context with three parts:
`state`, `actions`, and `meta`. This interface is a contract that any provider
can implement—enabling the same UI components to work with completely different
state implementations.
**Core principle:** Lift state, compose internals, make state
dependency-injectable.
**Incorrect (UI coupled to specific state implementation):**
```tsx
function ComposerInput() {
// Tightly coupled to a specific hook
const { input, setInput } = useChannelComposerState()
return <TextInput value={input} onChangeText={setInput} />
}
```
**Correct (generic interface enables dependency injection):**
```tsx
// Define a GENERIC interface that any provider can implement
interface ComposerState {
input: string
attachments: Attachment[]
isSubmitting: boolean
}
interface ComposerActions {
update: (updater: (state: ComposerState) => ComposerState) => void
submit: () => void
}
interface ComposerMeta {
inputRef: React.RefObject<TextInput>
}
interface ComposerContextValue {
state: ComposerState
actions: ComposerActions
meta: ComposerMeta
}
const ComposerContext = createContext<ComposerContextValue | null>(null)
```
**UI components consume the interface, not the implementation:**
```tsx
function ComposerInput() {
const {
state,
actions: { update },
meta,
} = use(ComposerContext)
// This component works with ANY provider that implements the interface
return (
<TextInput
ref={meta.inputRef}
value={state.input}
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
/>
)
}
```
**Different providers implement the same interface:**
```tsx
// Provider A: Local state for ephemeral forms
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState(initialState)
const inputRef = useRef(null)
const submit = useForwardMessage()
return (
<ComposerContext
value={{
state,
actions: { update: setState, submit },
meta: { inputRef },
}}
>
{children}
</ComposerContext>
)
}
// Provider B: Global synced state for channels
function ChannelProvider({ channelId, children }: Props) {
const { state, update, submit } = useGlobalChannel(channelId)
const inputRef = useRef(null)
return (
<ComposerContext
value={{
state,
actions: { update, submit },
meta: { inputRef },
}}
>
{children}
</ComposerContext>
)
}
```
**The same composed UI works with both:**
```tsx
// Works with ForwardMessageProvider (local state)
<ForwardMessageProvider>
<Composer.Frame>
<Composer.Input />
<Composer.Submit />
</Composer.Frame>
</ForwardMessageProvider>
// Works with ChannelProvider (global synced state)
<ChannelProvider channelId="abc">
<Composer.Frame>
<Composer.Input />
<Composer.Submit />
</Composer.Frame>
</ChannelProvider>
```
**Custom UI outside the component can access state and actions:**
The provider boundary is what matters—not the visual nesting. Components that
need shared state don't have to be inside the `Composer.Frame`. They just need
to be within the provider.
```tsx
function ForwardMessageDialog() {
return (
<ForwardMessageProvider>
<Dialog>
{/* The composer UI */}
<Composer.Frame>
<Composer.Input placeholder="Add a message, if you'd like." />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
</Composer.Footer>
</Composer.Frame>
{/* Custom UI OUTSIDE the composer, but INSIDE the provider */}
<MessagePreview />
{/* Actions at the bottom of the dialog */}
<DialogActions>
<CancelButton />
<ForwardButton />
</DialogActions>
</Dialog>
</ForwardMessageProvider>
)
}
// This button lives OUTSIDE Composer.Frame but can still submit based on its context!
function ForwardButton() {
const {
actions: { submit },
} = use(ComposerContext)
return <Button onPress={submit}>Forward</Button>
}
// This preview lives OUTSIDE Composer.Frame but can read composer's state!
function MessagePreview() {
const { state } = use(ComposerContext)
return <Preview message={state.input} attachments={state.attachments} />
}
```
The `ForwardButton` and `MessagePreview` are not visually inside the composer
box, but they can still access its state and actions. This is the power of
lifting state into providers.
The UI is reusable bits you compose together. The state is dependency-injected
by the provider. Swap the provider, keep the UI.
---
title: Decouple State Management from UI
impact: MEDIUM
impactDescription: enables swapping state implementations without changing UI
tags: composition, state, architecture
---
## Decouple State Management from UI
The provider component should be the only place that knows how state is managed.
UI components consume the context interface—they don't know if state comes from
useState, Zustand, or a server sync.
**Incorrect (UI coupled to state implementation):**
```tsx
function ChannelComposer({ channelId }: { channelId: string }) {
// UI component knows about global state implementation
const state = useGlobalChannelState(channelId)
const { submit, updateInput } = useChannelSync(channelId)
return (
<Composer.Frame>
<Composer.Input
value={state.input}
onChange={(text) => sync.updateInput(text)}
/>
<Composer.Submit onPress={() => sync.submit()} />
</Composer.Frame>
)
}
```
**Correct (state management isolated in provider):**
```tsx
// Provider handles all state management details
function ChannelProvider({
channelId,
children,
}: {
channelId: string
children: React.ReactNode
}) {
const { state, update, submit } = useGlobalChannel(channelId)
const inputRef = useRef(null)
return (
<Composer.Provider
state={state}
actions={{ update, submit }}
meta={{ inputRef }}
>
{children}
</Composer.Provider>
)
}
// UI component only knows about the context interface
function ChannelComposer() {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Usage
function Channel({ channelId }: { channelId: string }) {
return (
<ChannelProvider channelId={channelId}>
<ChannelComposer />
</ChannelProvider>
)
}
```
**Different providers, same UI:**
```tsx
// Local state for ephemeral forms
function ForwardMessageProvider({ children }) {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
return (
<Composer.Provider
state={state}
actions={{ update: setState, submit: forwardMessage }}
>
{children}
</Composer.Provider>
)
}
// Global synced state for channels
function ChannelProvider({ channelId, children }) {
const { state, update, submit } = useGlobalChannel(channelId)
return (
<Composer.Provider state={state} actions={{ update, submit }}>
{children}
</Composer.Provider>
)
}
```
The same `Composer.Input` component works with both providers because it only
depends on the context interface, not the implementation.
---
title: Lift State into Provider Components
impact: HIGH
impactDescription: enables state sharing outside component boundaries
tags: composition, state, context, providers
---
## Lift State into Provider Components
Move state management into dedicated provider components. This allows sibling
components outside the main UI to access and modify state without prop drilling
or awkward refs.
**Incorrect (state trapped inside component):**
```tsx
function ForwardMessageComposer() {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
return (
<Composer.Frame>
<Composer.Input />
<Composer.Footer />
</Composer.Frame>
)
}
// Problem: How does this button access composer state?
function ForwardMessageDialog() {
return (
<Dialog>
<ForwardMessageComposer />
<MessagePreview /> {/* Needs composer state */}
<DialogActions>
<CancelButton />
<ForwardButton /> {/* Needs to call submit */}
</DialogActions>
</Dialog>
)
}
```
**Incorrect (useEffect to sync state up):**
```tsx
function ForwardMessageDialog() {
const [input, setInput] = useState('')
return (
<Dialog>
<ForwardMessageComposer onInputChange={setInput} />
<MessagePreview input={input} />
</Dialog>
)
}
function ForwardMessageComposer({ onInputChange }) {
const [state, setState] = useState(initialState)
useEffect(() => {
onInputChange(state.input) // Sync on every change 😬
}, [state.input])
}
```
**Incorrect (reading state from ref on submit):**
```tsx
function ForwardMessageDialog() {
const stateRef = useRef(null)
return (
<Dialog>
<ForwardMessageComposer stateRef={stateRef} />
<ForwardButton onPress={() => submit(stateRef.current)} />
</Dialog>
)
}
```
**Correct (state lifted to provider):**
```tsx
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
const inputRef = useRef(null)
return (
<Composer.Provider
state={state}
actions={{ update: setState, submit: forwardMessage }}
meta={{ inputRef }}
>
{children}
</Composer.Provider>
)
}
function ForwardMessageDialog() {
return (
<ForwardMessageProvider>
<Dialog>
<ForwardMessageComposer />
<MessagePreview /> {/* Custom components can access state and actions */}
<DialogActions>
<CancelButton />
<ForwardButton /> {/* Custom components can access state and actions */}
</DialogActions>
</Dialog>
</ForwardMessageProvider>
)
}
function ForwardButton() {
const { actions } = use(Composer.Context)
return <Button onPress={actions.submit}>Forward</Button>
}
```
The ForwardButton lives outside the Composer.Frame but still has access to the
submit action because it's within the provider. Even though it's a one-off
component, it can still access the composer's state and actions from outside the
UI itself.
**Key insight:** Components that need shared state don't have to be visually
nested inside each other—they just need to be within the same provider.
This source diff could not be displayed because it is too large. You can view the blob instead.
# React Best Practices
A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs.
## Structure
- `rules/` - Individual rule files (one per rule)
- `_sections.md` - Section metadata (titles, impacts, descriptions)
- `_template.md` - Template for creating new rules
- `area-description.md` - Individual rule files
- `src/` - Build scripts and utilities
- `metadata.json` - Document metadata (version, organization, abstract)
- __`AGENTS.md`__ - Compiled output (generated)
- __`test-cases.json`__ - Test cases for LLM evaluation (generated)
## Getting Started
1. Install dependencies:
```bash
pnpm install
```
2. Build AGENTS.md from rules:
```bash
pnpm build
```
3. Validate rule files:
```bash
pnpm validate
```
4. Extract test cases:
```bash
pnpm extract-tests
```
## Creating a New Rule
1. Copy `rules/_template.md` to `rules/area-description.md`
2. Choose the appropriate area prefix:
- `async-` for Eliminating Waterfalls (Section 1)
- `bundle-` for Bundle Size Optimization (Section 2)
- `server-` for Server-Side Performance (Section 3)
- `client-` for Client-Side Data Fetching (Section 4)
- `rerender-` for Re-render Optimization (Section 5)
- `rendering-` for Rendering Performance (Section 6)
- `js-` for JavaScript Performance (Section 7)
- `advanced-` for Advanced Patterns (Section 8)
3. Fill in the frontmatter and content
4. Ensure you have clear examples with explanations
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
## Rule File Structure
Each rule file should follow this structure:
```markdown
---
title: Rule Title Here
impact: MEDIUM
impactDescription: Optional description
tags: tag1, tag2, tag3
---
## Rule Title Here
Brief explanation of the rule and why it matters.
**Incorrect (description of what's wrong):**
```typescript
// Bad code example
```
**Correct (description of what's right):**
```typescript
// Good code example
```
Optional explanatory text after examples.
Reference: [Link](https://example.com)
## File Naming Convention
- Files starting with `_` are special (excluded from build)
- Rule files: `area-description.md` (e.g., `async-parallel.md`)
- Section is automatically inferred from filename prefix
- Rules are sorted alphabetically by title within each section
- IDs (e.g., 1.1, 1.2) are auto-generated during build
## Impact Levels
- `CRITICAL` - Highest priority, major performance gains
- `HIGH` - Significant performance improvements
- `MEDIUM-HIGH` - Moderate-high gains
- `MEDIUM` - Moderate performance improvements
- `LOW-MEDIUM` - Low-medium gains
- `LOW` - Incremental improvements
## Scripts
- `pnpm build` - Compile rules into AGENTS.md
- `pnpm validate` - Validate all rule files
- `pnpm extract-tests` - Extract test cases for LLM evaluation
- `pnpm dev` - Build and validate
## Contributing
When adding or modifying rules:
1. Use the correct filename prefix for your section
2. Follow the `_template.md` structure
3. Include clear bad/good examples with explanations
4. Add appropriate tags
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
6. Rules are automatically sorted by title - no need to manage numbers!
## Acknowledgments
Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).
---
name: vercel-react-best-practices
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
license: MIT
metadata:
author: vercel
version: "1.0.0"
---
# Vercel React Best Practices
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 70 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
## When to Apply
Reference these guidelines when:
- Writing new React components or Next.js pages
- Implementing data fetching (client or server-side)
- Reviewing code for performance issues
- Refactoring existing React/Next.js code
- Optimizing bundle size or load times
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
| 3 | Server-Side Performance | HIGH | `server-` |
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
| 6 | Rendering Performance | MEDIUM | `rendering-` |
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
| 8 | Advanced Patterns | LOW | `advanced-` |
## Quick Reference
### 1. Eliminating Waterfalls (CRITICAL)
- `async-cheap-condition-before-await` - Check cheap sync conditions before awaiting flags or remote values
- `async-defer-await` - Move await into branches where actually used
- `async-parallel` - Use Promise.all() for independent operations
- `async-dependencies` - Use better-all for partial dependencies
- `async-api-routes` - Start promises early, await late in API routes
- `async-suspense-boundaries` - Use Suspense to stream content
### 2. Bundle Size Optimization (CRITICAL)
- `bundle-barrel-imports` - Import directly, avoid barrel files
- `bundle-analyzable-paths` - Prefer statically analyzable import and file-system paths to avoid broad bundles and traces
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
- `bundle-defer-third-party` - Load analytics/logging after hydration
- `bundle-conditional` - Load modules only when feature is activated
- `bundle-preload` - Preload on hover/focus for perceived speed
### 3. Server-Side Performance (HIGH)
- `server-auth-actions` - Authenticate server actions like API routes
- `server-cache-react` - Use React.cache() for per-request deduplication
- `server-cache-lru` - Use LRU cache for cross-request caching
- `server-dedup-props` - Avoid duplicate serialization in RSC props
- `server-hoist-static-io` - Hoist static I/O (fonts, logos) to module level
- `server-no-shared-module-state` - Avoid module-level mutable request state in RSC/SSR
- `server-serialization` - Minimize data passed to client components
- `server-parallel-fetching` - Restructure components to parallelize fetches
- `server-parallel-nested-fetching` - Chain nested fetches per item in Promise.all
- `server-after-nonblocking` - Use after() for non-blocking operations
### 4. Client-Side Data Fetching (MEDIUM-HIGH)
- `client-swr-dedup` - Use SWR for automatic request deduplication
- `client-event-listeners` - Deduplicate global event listeners
- `client-passive-event-listeners` - Use passive listeners for scroll
- `client-localstorage-schema` - Version and minimize localStorage data
### 5. Re-render Optimization (MEDIUM)
- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
- `rerender-memo` - Extract expensive work into memoized components
- `rerender-memo-with-default-value` - Hoist default non-primitive props
- `rerender-dependencies` - Use primitive dependencies in effects
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
- `rerender-derived-state-no-effect` - Derive state during render, not effects
- `rerender-functional-setstate` - Use functional setState for stable callbacks
- `rerender-lazy-state-init` - Pass function to useState for expensive values
- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives
- `rerender-split-combined-hooks` - Split hooks with independent dependencies
- `rerender-move-effect-to-event` - Put interaction logic in event handlers
- `rerender-transitions` - Use startTransition for non-urgent updates
- `rerender-use-deferred-value` - Defer expensive renders to keep input responsive
- `rerender-use-ref-transient-values` - Use refs for transient frequent values
- `rerender-no-inline-components` - Don't define components inside components
### 6. Rendering Performance (MEDIUM)
- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
- `rendering-content-visibility` - Use content-visibility for long lists
- `rendering-hoist-jsx` - Extract static JSX outside components
- `rendering-svg-precision` - Reduce SVG coordinate precision
- `rendering-hydration-no-flicker` - Use inline script for client-only data
- `rendering-hydration-suppress-warning` - Suppress expected mismatches
- `rendering-activity` - Use Activity component for show/hide
- `rendering-conditional-render` - Use ternary, not && for conditionals
- `rendering-usetransition-loading` - Prefer useTransition for loading state
- `rendering-resource-hints` - Use React DOM resource hints for preloading
- `rendering-script-defer-async` - Use defer or async on script tags
### 7. JavaScript Performance (LOW-MEDIUM)
- `js-batch-dom-css` - Group CSS changes via classes or cssText
- `js-index-maps` - Build Map for repeated lookups
- `js-cache-property-access` - Cache object properties in loops
- `js-cache-function-results` - Cache function results in module-level Map
- `js-cache-storage` - Cache localStorage/sessionStorage reads
- `js-combine-iterations` - Combine multiple filter/map into one loop
- `js-length-check-first` - Check array length before expensive comparison
- `js-early-exit` - Return early from functions
- `js-hoist-regexp` - Hoist RegExp creation outside loops
- `js-min-max-loop` - Use loop for min/max instead of sort
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
- `js-tosorted-immutable` - Use toSorted() for immutability
- `js-flatmap-filter` - Use flatMap to map and filter in one pass
- `js-request-idle-callback` - Defer non-critical work to browser idle time
### 8. Advanced Patterns (LOW)
- `advanced-effect-event-deps` - Don't put `useEffectEvent` results in effect deps
- `advanced-event-handler-refs` - Store event handlers in refs
- `advanced-init-once` - Initialize app once per app load
- `advanced-use-latest` - useLatest for stable callback refs
## How to Use
Read individual rule files for detailed explanations and code examples:
```
rules/async-parallel.md
rules/bundle-barrel-imports.md
```
Each rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Additional context and references
## Full Compiled Document
For the complete guide with all rules expanded: `AGENTS.md`
{
"version": "1.0.0",
"organization": "Vercel Engineering",
"date": "January 2026",
"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.",
"references": [
"https://react.dev",
"https://nextjs.org",
"https://swr.vercel.app",
"https://github.com/shuding/better-all",
"https://github.com/isaacs/node-lru-cache",
"https://vercel.com/blog/how-we-optimized-package-imports-in-next-js",
"https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast"
]
}
# Sections
This file defines all sections, their ordering, impact levels, and descriptions.
The section ID (in parentheses) is the filename prefix used to group rules.
---
## 1. Eliminating Waterfalls (async)
**Impact:** CRITICAL
**Description:** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
## 2. Bundle Size Optimization (bundle)
**Impact:** CRITICAL
**Description:** Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
## 3. Server-Side Performance (server)
**Impact:** HIGH
**Description:** Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
## 4. Client-Side Data Fetching (client)
**Impact:** MEDIUM-HIGH
**Description:** Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
## 5. Re-render Optimization (rerender)
**Impact:** MEDIUM
**Description:** Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
## 6. Rendering Performance (rendering)
**Impact:** MEDIUM
**Description:** Optimizing the rendering process reduces the work the browser needs to do.
## 7. JavaScript Performance (js)
**Impact:** LOW-MEDIUM
**Description:** Micro-optimizations for hot paths can add up to meaningful improvements.
## 8. Advanced Patterns (advanced)
**Impact:** LOW
**Description:** Advanced patterns for specific cases that require careful implementation.
---
title: Rule Title Here
impact: MEDIUM
impactDescription: Optional description of impact (e.g., "20-50% improvement")
tags: tag1, tag2
---
## Rule Title Here
**Impact: MEDIUM (optional impact description)**
Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications.
**Incorrect (description of what's wrong):**
```typescript
// Bad code example here
const bad = example()
```
**Correct (description of what's right):**
```typescript
// Good code example here
const good = example()
```
Reference: [Link to documentation or resource](https://example.com)
---
title: Do Not Put Effect Events in Dependency Arrays
impact: LOW
impactDescription: avoids unnecessary effect re-runs and lint errors
tags: advanced, hooks, useEffectEvent, dependencies, effects
---
## Do Not Put Effect Events in Dependency Arrays
Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
**Incorrect (Effect Event added as a dependency):**
```tsx
import { useEffect, useEffectEvent } from 'react'
function ChatRoom({ roomId, onConnected }: {
roomId: string
onConnected: () => void
}) {
const handleConnected = useEffectEvent(onConnected)
useEffect(() => {
const connection = createConnection(roomId)
connection.on('connected', handleConnected)
connection.connect()
return () => connection.disconnect()
}, [roomId, handleConnected])
}
```
Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.
**Correct (depend on reactive values, not the Effect Event):**
```tsx
import { useEffect, useEffectEvent } from 'react'
function ChatRoom({ roomId, onConnected }: {
roomId: string
onConnected: () => void
}) {
const handleConnected = useEffectEvent(onConnected)
useEffect(() => {
const connection = createConnection(roomId)
connection.on('connected', handleConnected)
connection.connect()
return () => connection.disconnect()
}, [roomId])
}
```
Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)
---
title: Store Event Handlers in Refs
impact: LOW
impactDescription: stable subscriptions
tags: advanced, hooks, refs, event-handlers, optimization
---
## Store Event Handlers in Refs
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
**Incorrect (re-subscribes on every render):**
```tsx
function useWindowEvent(event: string, handler: (e) => void) {
useEffect(() => {
window.addEventListener(event, handler)
return () => window.removeEventListener(event, handler)
}, [event, handler])
}
```
**Correct (stable subscription):**
```tsx
function useWindowEvent(event: string, handler: (e) => void) {
const handlerRef = useRef(handler)
useEffect(() => {
handlerRef.current = handler
}, [handler])
useEffect(() => {
const listener = (e) => handlerRef.current(e)
window.addEventListener(event, listener)
return () => window.removeEventListener(event, listener)
}, [event])
}
```
**Alternative: use `useEffectEvent` if you're on latest React:**
```tsx
import { useEffectEvent } from 'react'
function useWindowEvent(event: string, handler: (e) => void) {
const onEvent = useEffectEvent(handler)
useEffect(() => {
window.addEventListener(event, onEvent)
return () => window.removeEventListener(event, onEvent)
}, [event])
}
```
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
---
title: Initialize App Once, Not Per Mount
impact: LOW-MEDIUM
impactDescription: avoids duplicate init in development
tags: initialization, useEffect, app-startup, side-effects
---
## Initialize App Once, Not Per Mount
Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
**Incorrect (runs twice in dev, re-runs on remount):**
```tsx
function Comp() {
useEffect(() => {
loadFromStorage()
checkAuthToken()
}, [])
// ...
}
```
**Correct (once per app load):**
```tsx
let didInit = false
function Comp() {
useEffect(() => {
if (didInit) return
didInit = true
loadFromStorage()
checkAuthToken()
}, [])
// ...
}
```
Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
---
title: useEffectEvent for Stable Callback Refs
impact: LOW
impactDescription: prevents effect re-runs
tags: advanced, hooks, useEffectEvent, refs, optimization
---
## useEffectEvent for Stable Callback Refs
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
**Incorrect (effect re-runs on every callback change):**
```tsx
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('')
useEffect(() => {
const timeout = setTimeout(() => onSearch(query), 300)
return () => clearTimeout(timeout)
}, [query, onSearch])
}
```
**Correct (using React's useEffectEvent):**
```tsx
import { useEffectEvent } from 'react';
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('')
const onSearchEvent = useEffectEvent(onSearch)
useEffect(() => {
const timeout = setTimeout(() => onSearchEvent(query), 300)
return () => clearTimeout(timeout)
}, [query])
}
```
---
title: Prevent Waterfall Chains in API Routes
impact: CRITICAL
impactDescription: 2-10× improvement
tags: api-routes, server-actions, waterfalls, parallelization
---
## Prevent Waterfall Chains in API Routes
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).
---
title: Check Cheap Conditions Before Async Flags
impact: HIGH
impactDescription: avoids unnecessary async work when a synchronous guard already fails
tags: async, await, feature-flags, short-circuit, conditional
---
## Check Cheap Conditions Before Async Flags
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.
---
title: Defer Await Until Needed
impact: HIGH
impactDescription: avoids blocking unused code paths
tags: async, await, conditional, optimization
---
## Defer Await Until Needed
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).
---
title: Dependency-Based Parallelization
impact: CRITICAL
impactDescription: 2-10× improvement
tags: async, parallelization, dependencies, better-all
---
## Dependency-Based Parallelization
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:**
We can also create all the promises first, and do `Promise.all()` at the end.
```typescript
const userPromise = fetchUser()
const profilePromise = userPromise.then(user => fetchProfile(user.id))
const [user, config, profile] = await Promise.all([
userPromise,
fetchConfig(),
profilePromise
])
```
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
---
title: Promise.all() for Independent Operations
impact: CRITICAL
impactDescription: 2-10× improvement
tags: async, parallelization, promises, waterfalls
---
## Promise.all() for Independent Operations
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()
])
```
---
title: Strategic Suspense Boundaries
impact: HIGH
impactDescription: faster initial paint
tags: async, suspense, streaming, layout-shift
---
## Strategic Suspense Boundaries
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 (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<DataDisplay data={data} />
</div>
<div>Footer</div>
</div>
)
}
```
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 (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<Suspense fallback={<Skeleton />}>
<DataDisplay />
</Suspense>
</div>
<div>Footer</div>
</div>
)
}
async function DataDisplay() {
const data = await fetchData() // Only blocks this component
return <div>{data.content}</div>
}
```
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 (
<div>
<div>Sidebar</div>
<div>Header</div>
<Suspense fallback={<Skeleton />}>
<DataDisplay dataPromise={dataPromise} />
<DataSummary dataPromise={dataPromise} />
</Suspense>
<div>Footer</div>
</div>
)
}
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
const data = use(dataPromise) // Unwraps the promise
return <div>{data.content}</div>
}
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
const data = use(dataPromise) // Reuses the same promise
return <div>{data.summary}</div>
}
```
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.
---
title: Prefer Statically Analyzable Paths
impact: HIGH
impactDescription: avoids accidental broad bundles and file traces
tags: bundle, nextjs, vite, webpack, rollup, esbuild, path
---
## Prefer Statically Analyzable Paths
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
### Import Paths
**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]()
```
### File-System Paths
**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: [Next.js output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [Next.js dynamic imports](https://nextjs.org/learn/seo/dynamic-imports), [Vite features](https://vite.dev/guide/features.html), [esbuild API](https://esbuild.github.io/api/), [Rollup dynamic import vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [Webpack dependency management](https://webpack.js.org/guides/dependency-management/)
---
title: Avoid Barrel File Imports
impact: CRITICAL
impactDescription: 200-800ms import cost, slow builds
tags: bundle, imports, tree-shaking, barrel-files, performance
---
## Avoid Barrel File Imports
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):**
```js
// next.config.js - automatically optimizes barrel imports at build time
module.exports = {
experimental: {
optimizePackageImports: ['lucide-react', '@mui/material']
}
}
```
```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: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
---
title: Conditional Module Loading
impact: HIGH
impactDescription: loads large data only when needed
tags: bundle, conditional-loading, lazy-loading
---
## Conditional Module Loading
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<React.SetStateAction<boolean>> }) {
const [frames, setFrames] = useState<Frame[] | null>(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 <Skeleton />
return <Canvas frames={frames} />
}
```
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
---
title: Defer Non-Critical Third-Party Libraries
impact: MEDIUM
impactDescription: loads after hydration
tags: bundle, third-party, analytics, defer
---
## Defer Non-Critical Third-Party Libraries
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 (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
```
**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 (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
```
---
title: Dynamic Imports for Heavy Components
impact: CRITICAL
impactDescription: directly affects TTI and LCP
tags: bundle, dynamic-import, code-splitting, next-dynamic
---
## Dynamic Imports for Heavy Components
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 <MonacoEditor value={code} />
}
```
**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 <MonacoEditor value={code} />
}
```
---
title: Preload Based on User Intent
impact: MEDIUM
impactDescription: reduces perceived latency
tags: bundle, preload, user-intent, hover
---
## Preload Based on User Intent
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 (
<button
onMouseEnter={preload}
onFocus={preload}
onClick={onClick}
>
Open Editor
</button>
)
}
```
**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 <FlagsContext.Provider value={flags}>
{children}
</FlagsContext.Provider>
}
```
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
---
title: Deduplicate Global Event Listeners
impact: LOW
impactDescription: single listener for N components
tags: client, swr, event-listeners, subscription
---
## Deduplicate Global Event Listeners
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<string, Set<() => 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', () => { /* ... */ })
// ...
}
```
---
title: Version and Minimize localStorage Data
impact: MEDIUM
impactDescription: prevents schema conflicts, reduces storage size
tags: client, localStorage, storage, versioning, data-minimization
---
## Version and Minimize localStorage Data
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.
---
title: Use Passive Event Listeners for Scrolling Performance
impact: MEDIUM
impactDescription: eliminates scroll delay caused by event listeners
tags: client, event-listeners, scrolling, performance, touch, wheel
---
## Use Passive Event Listeners for Scrolling Performance
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()`.
---
title: Use SWR for Automatic Deduplication
impact: MEDIUM-HIGH
impactDescription: automatic deduplication
tags: client, swr, deduplication, data-fetching
---
## Use SWR for 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 <button onClick={() => trigger()}>Update</button>
}
```
Reference: [https://swr.vercel.app](https://swr.vercel.app)
---
title: Avoid Layout Thrashing
impact: MEDIUM
impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks
tags: javascript, dom, css, performance, reflow, layout-thrashing
---
## Avoid Layout Thrashing
Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
**This is OK (browser batches style changes):**
```typescript
function updateElementStyles(element: HTMLElement) {
// Each line invalidates style, but browser batches the recalculation
element.style.width = '100px'
element.style.height = '200px'
element.style.backgroundColor = 'blue'
element.style.border = '1px solid black'
}
```
**Incorrect (interleaved reads and writes force reflows):**
```typescript
function layoutThrashing(element: HTMLElement) {
element.style.width = '100px'
const width = element.offsetWidth // Forces reflow
element.style.height = '200px'
const height = element.offsetHeight // Forces another reflow
}
```
**Correct (batch writes, then read once):**
```typescript
function updateElementStyles(element: HTMLElement) {
// Batch all writes together
element.style.width = '100px'
element.style.height = '200px'
element.style.backgroundColor = 'blue'
element.style.border = '1px solid black'
// Read after all writes are done (single reflow)
const { width, height } = element.getBoundingClientRect()
}
```
**Correct (batch reads, then writes):**
```typescript
function avoidThrashing(element: HTMLElement) {
// Read phase - all layout queries first
const rect1 = element.getBoundingClientRect()
const offsetWidth = element.offsetWidth
const offsetHeight = element.offsetHeight
// Write phase - all style changes after
element.style.width = '100px'
element.style.height = '200px'
}
```
**Better: use CSS classes**
```css
.highlighted-box {
width: 100px;
height: 200px;
background-color: blue;
border: 1px solid black;
}
```
```typescript
function updateElementStyles(element: HTMLElement) {
element.classList.add('highlighted-box')
const { width, height } = element.getBoundingClientRect()
}
```
**React example:**
```tsx
// Incorrect: interleaving style changes with layout queries
function Box({ isHighlighted }: { isHighlighted: boolean }) {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
if (ref.current && isHighlighted) {
ref.current.style.width = '100px'
const width = ref.current.offsetWidth // Forces layout
ref.current.style.height = '200px'
}
}, [isHighlighted])
return <div ref={ref}>Content</div>
}
// Correct: toggle class
function Box({ isHighlighted }: { isHighlighted: boolean }) {
return (
<div className={isHighlighted ? 'highlighted-box' : ''}>
Content
</div>
)
}
```
Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
---
title: Cache Repeated Function Calls
impact: MEDIUM
impactDescription: avoid redundant computation
tags: javascript, cache, memoization, performance
---
## Cache Repeated Function Calls
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
**Incorrect (redundant computation):**
```typescript
function ProjectList({ projects }: { projects: Project[] }) {
return (
<div>
{projects.map(project => {
// slugify() called 100+ times for same project names
const slug = slugify(project.name)
return <ProjectCard key={project.id} slug={slug} />
})}
</div>
)
}
```
**Correct (cached results):**
```typescript
// Module-level cache
const slugifyCache = new Map<string, string>()
function cachedSlugify(text: string): string {
if (slugifyCache.has(text)) {
return slugifyCache.get(text)!
}
const result = slugify(text)
slugifyCache.set(text, result)
return result
}
function ProjectList({ projects }: { projects: Project[] }) {
return (
<div>
{projects.map(project => {
// Computed only once per unique project name
const slug = cachedSlugify(project.name)
return <ProjectCard key={project.id} slug={slug} />
})}
</div>
)
}
```
**Simpler pattern for single-value functions:**
```typescript
let isLoggedInCache: boolean | null = null
function isLoggedIn(): boolean {
if (isLoggedInCache !== null) {
return isLoggedInCache
}
isLoggedInCache = document.cookie.includes('auth=')
return isLoggedInCache
}
// Clear cache when auth changes
function onAuthChange() {
isLoggedInCache = null
}
```
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
---
title: Cache Property Access in Loops
impact: LOW-MEDIUM
impactDescription: reduces lookups
tags: javascript, loops, optimization, caching
---
## Cache Property Access in Loops
Cache object property lookups in hot paths.
**Incorrect (3 lookups × N iterations):**
```typescript
for (let i = 0; i < arr.length; i++) {
process(obj.config.settings.value)
}
```
**Correct (1 lookup total):**
```typescript
const value = obj.config.settings.value
const len = arr.length
for (let i = 0; i < len; i++) {
process(value)
}
```
---
title: Cache Storage API Calls
impact: LOW-MEDIUM
impactDescription: reduces expensive I/O
tags: javascript, localStorage, storage, caching, performance
---
## Cache Storage API Calls
`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
**Incorrect (reads storage on every call):**
```typescript
function getTheme() {
return localStorage.getItem('theme') ?? 'light'
}
// Called 10 times = 10 storage reads
```
**Correct (Map cache):**
```typescript
const storageCache = new Map<string, string | null>()
function getLocalStorage(key: string) {
if (!storageCache.has(key)) {
storageCache.set(key, localStorage.getItem(key))
}
return storageCache.get(key)
}
function setLocalStorage(key: string, value: string) {
localStorage.setItem(key, value)
storageCache.set(key, value) // keep cache in sync
}
```
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
**Cookie caching:**
```typescript
let cookieCache: Record<string, string> | null = null
function getCookie(name: string) {
if (!cookieCache) {
cookieCache = Object.fromEntries(
document.cookie.split('; ').map(c => c.split('='))
)
}
return cookieCache[name]
}
```
**Important (invalidate on external changes):**
If storage can change externally (another tab, server-set cookies), invalidate cache:
```typescript
window.addEventListener('storage', (e) => {
if (e.key) storageCache.delete(e.key)
})
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
storageCache.clear()
}
})
```
---
title: Combine Multiple Array Iterations
impact: LOW-MEDIUM
impactDescription: reduces iterations
tags: javascript, arrays, loops, performance
---
## Combine Multiple Array Iterations
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
**Incorrect (3 iterations):**
```typescript
const admins = users.filter(u => u.isAdmin)
const testers = users.filter(u => u.isTester)
const inactive = users.filter(u => !u.isActive)
```
**Correct (1 iteration):**
```typescript
const admins: User[] = []
const testers: User[] = []
const inactive: User[] = []
for (const user of users) {
if (user.isAdmin) admins.push(user)
if (user.isTester) testers.push(user)
if (!user.isActive) inactive.push(user)
}
```
---
title: Early Return from Functions
impact: LOW-MEDIUM
impactDescription: avoids unnecessary computation
tags: javascript, functions, optimization, early-return
---
## Early Return from Functions
Return early when result is determined to skip unnecessary processing.
**Incorrect (processes all items even after finding answer):**
```typescript
function validateUsers(users: User[]) {
let hasError = false
let errorMessage = ''
for (const user of users) {
if (!user.email) {
hasError = true
errorMessage = 'Email required'
}
if (!user.name) {
hasError = true
errorMessage = 'Name required'
}
// Continues checking all users even after error found
}
return hasError ? { valid: false, error: errorMessage } : { valid: true }
}
```
**Correct (returns immediately on first error):**
```typescript
function validateUsers(users: User[]) {
for (const user of users) {
if (!user.email) {
return { valid: false, error: 'Email required' }
}
if (!user.name) {
return { valid: false, error: 'Name required' }
}
}
return { valid: true }
}
```
---
title: Use flatMap to Map and Filter in One Pass
impact: LOW-MEDIUM
impactDescription: eliminates intermediate array
tags: javascript, arrays, flatMap, filter, performance
---
## Use flatMap to Map and Filter in One Pass
**Impact: LOW-MEDIUM (eliminates intermediate array)**
Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.
**Incorrect (2 iterations, intermediate array):**
```typescript
const userNames = users
.map(user => user.isActive ? user.name : null)
.filter(Boolean)
```
**Correct (1 iteration, no intermediate array):**
```typescript
const userNames = users.flatMap(user =>
user.isActive ? [user.name] : []
)
```
**More examples:**
```typescript
// Extract valid emails from responses
// Before
const emails = responses
.map(r => r.success ? r.data.email : null)
.filter(Boolean)
// After
const emails = responses.flatMap(r =>
r.success ? [r.data.email] : []
)
// Parse and filter valid numbers
// Before
const numbers = strings
.map(s => parseInt(s, 10))
.filter(n => !isNaN(n))
// After
const numbers = strings.flatMap(s => {
const n = parseInt(s, 10)
return isNaN(n) ? [] : [n]
})
```
**When to use:**
- Transforming items while filtering some out
- Conditional mapping where some inputs produce no output
- Parsing/validating where invalid inputs should be skipped
---
title: Hoist RegExp Creation
impact: LOW-MEDIUM
impactDescription: avoids recreation
tags: javascript, regexp, optimization, memoization
---
## Hoist RegExp Creation
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
**Incorrect (new RegExp every render):**
```tsx
function Highlighter({ text, query }: Props) {
const regex = new RegExp(`(${query})`, 'gi')
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
```
**Correct (memoize or hoist):**
```tsx
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
function Highlighter({ text, query }: Props) {
const regex = useMemo(
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
[query]
)
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
```
**Warning (global regex has mutable state):**
Global regex (`/g`) has mutable `lastIndex` state:
```typescript
const regex = /foo/g
regex.test('foo') // true, lastIndex = 3
regex.test('foo') // false, lastIndex = 0
```
---
title: Build Index Maps for Repeated Lookups
impact: LOW-MEDIUM
impactDescription: 1M ops to 2K ops
tags: javascript, map, indexing, optimization, performance
---
## Build Index Maps for Repeated Lookups
Multiple `.find()` calls by the same key should use a Map.
**Incorrect (O(n) per lookup):**
```typescript
function processOrders(orders: Order[], users: User[]) {
return orders.map(order => ({
...order,
user: users.find(u => u.id === order.userId)
}))
}
```
**Correct (O(1) per lookup):**
```typescript
function processOrders(orders: Order[], users: User[]) {
const userById = new Map(users.map(u => [u.id, u]))
return orders.map(order => ({
...order,
user: userById.get(order.userId)
}))
}
```
Build map once (O(n)), then all lookups are O(1).
For 1000 orders × 1000 users: 1M ops → 2K ops.
---
title: Early Length Check for Array Comparisons
impact: MEDIUM-HIGH
impactDescription: avoids expensive operations when lengths differ
tags: javascript, arrays, performance, optimization, comparison
---
## Early Length Check for Array Comparisons
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
**Incorrect (always runs expensive comparison):**
```typescript
function hasChanges(current: string[], original: string[]) {
// Always sorts and joins, even when lengths differ
return current.sort().join() !== original.sort().join()
}
```
Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
**Correct (O(1) length check first):**
```typescript
function hasChanges(current: string[], original: string[]) {
// Early return if lengths differ
if (current.length !== original.length) {
return true
}
// Only sort when lengths match
const currentSorted = current.toSorted()
const originalSorted = original.toSorted()
for (let i = 0; i < currentSorted.length; i++) {
if (currentSorted[i] !== originalSorted[i]) {
return true
}
}
return false
}
```
This new approach is more efficient because:
- It avoids the overhead of sorting and joining the arrays when lengths differ
- It avoids consuming memory for the joined strings (especially important for large arrays)
- It avoids mutating the original arrays
- It returns early when a difference is found
---
title: Use Loop for Min/Max Instead of Sort
impact: LOW
impactDescription: O(n) instead of O(n log n)
tags: javascript, arrays, performance, sorting, algorithms
---
## Use Loop for Min/Max Instead of Sort
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
**Incorrect (O(n log n) - sort to find latest):**
```typescript
interface Project {
id: string
name: string
updatedAt: number
}
function getLatestProject(projects: Project[]) {
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
return sorted[0]
}
```
Sorts the entire array just to find the maximum value.
**Incorrect (O(n log n) - sort for oldest and newest):**
```typescript
function getOldestAndNewest(projects: Project[]) {
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
}
```
Still sorts unnecessarily when only min/max are needed.
**Correct (O(n) - single loop):**
```typescript
function getLatestProject(projects: Project[]) {
if (projects.length === 0) return null
let latest = projects[0]
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt > latest.updatedAt) {
latest = projects[i]
}
}
return latest
}
function getOldestAndNewest(projects: Project[]) {
if (projects.length === 0) return { oldest: null, newest: null }
let oldest = projects[0]
let newest = projects[0]
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
}
return { oldest, newest }
}
```
Single pass through the array, no copying, no sorting.
**Alternative (Math.min/Math.max for small arrays):**
```typescript
const numbers = [5, 2, 8, 1, 9]
const min = Math.min(...numbers)
const max = Math.max(...numbers)
```
This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
---
title: Defer Non-Critical Work with requestIdleCallback
impact: MEDIUM
impactDescription: keeps UI responsive during background tasks
tags: javascript, performance, idle, scheduling, analytics
---
## Defer Non-Critical Work with requestIdleCallback
**Impact: MEDIUM (keeps UI responsive during background tasks)**
Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.
**Incorrect (blocks main thread during user interaction):**
```typescript
function handleSearch(query: string) {
const results = searchItems(query)
setResults(results)
// These block the main thread immediately
analytics.track('search', { query })
saveToRecentSearches(query)
prefetchTopResults(results.slice(0, 3))
}
```
**Correct (defers non-critical work to idle time):**
```typescript
function handleSearch(query: string) {
const results = searchItems(query)
setResults(results)
// Defer non-critical work to idle periods
requestIdleCallback(() => {
analytics.track('search', { query })
})
requestIdleCallback(() => {
saveToRecentSearches(query)
})
requestIdleCallback(() => {
prefetchTopResults(results.slice(0, 3))
})
}
```
**With timeout for required work:**
```typescript
// Ensure analytics fires within 2 seconds even if browser stays busy
requestIdleCallback(
() => analytics.track('page_view', { path: location.pathname }),
{ timeout: 2000 }
)
```
**Chunking large tasks:**
```typescript
function processLargeDataset(items: Item[]) {
let index = 0
function processChunk(deadline: IdleDeadline) {
// Process items while we have idle time (aim for <50ms chunks)
while (index < items.length && deadline.timeRemaining() > 0) {
processItem(items[index])
index++
}
// Schedule next chunk if more items remain
if (index < items.length) {
requestIdleCallback(processChunk)
}
}
requestIdleCallback(processChunk)
}
```
**With fallback for unsupported browsers:**
```typescript
const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1))
scheduleIdleWork(() => {
// Non-critical work
})
```
**When to use:**
- Analytics and telemetry
- Saving state to localStorage/IndexedDB
- Prefetching resources for likely next actions
- Processing non-urgent data transformations
- Lazy initialization of non-critical features
**When NOT to use:**
- User-initiated actions that need immediate feedback
- Rendering updates the user is waiting for
- Time-sensitive operations
---
title: Use Set/Map for O(1) Lookups
impact: LOW-MEDIUM
impactDescription: O(n) to O(1)
tags: javascript, set, map, data-structures, performance
---
## Use Set/Map for O(1) Lookups
Convert arrays to Set/Map for repeated membership checks.
**Incorrect (O(n) per check):**
```typescript
const allowedIds = ['a', 'b', 'c', ...]
items.filter(item => allowedIds.includes(item.id))
```
**Correct (O(1) per check):**
```typescript
const allowedIds = new Set(['a', 'b', 'c', ...])
items.filter(item => allowedIds.has(item.id))
```
---
title: Use toSorted() Instead of sort() for Immutability
impact: MEDIUM-HIGH
impactDescription: prevents mutation bugs in React state
tags: javascript, arrays, immutability, react, state, mutation
---
## Use toSorted() Instead of sort() for Immutability
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
**Incorrect (mutates original array):**
```typescript
function UserList({ users }: { users: User[] }) {
// Mutates the users prop array!
const sorted = useMemo(
() => users.sort((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
```
**Correct (creates new array):**
```typescript
function UserList({ users }: { users: User[] }) {
// Creates new sorted array, original unchanged
const sorted = useMemo(
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
```
**Why this matters in React:**
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
**Browser support (fallback for older browsers):**
`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
```typescript
// Fallback for older browsers
const sorted = [...items].sort((a, b) => a.value - b.value)
```
**Other immutable array methods:**
- `.toSorted()` - immutable sort
- `.toReversed()` - immutable reverse
- `.toSpliced()` - immutable splice
- `.with()` - immutable element replacement
---
title: Use Activity Component for Show/Hide
impact: MEDIUM
impactDescription: preserves state/DOM
tags: rendering, activity, visibility, state-preservation
---
## Use Activity Component for Show/Hide
Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
**Usage:**
```tsx
import { Activity } from 'react'
function Dropdown({ isOpen }: Props) {
return (
<Activity mode={isOpen ? 'visible' : 'hidden'}>
<ExpensiveMenu />
</Activity>
)
}
```
Avoids expensive re-renders and state loss.
---
title: Animate SVG Wrapper Instead of SVG Element
impact: LOW
impactDescription: enables hardware acceleration
tags: rendering, svg, css, animation, performance
---
## Animate SVG Wrapper Instead of SVG Element
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
**Incorrect (animating SVG directly - no hardware acceleration):**
```tsx
function LoadingSpinner() {
return (
<svg
className="animate-spin"
width="24"
height="24"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
)
}
```
**Correct (animating wrapper div - hardware accelerated):**
```tsx
function LoadingSpinner() {
return (
<div className="animate-spin">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
</div>
)
}
```
This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
---
title: Use Explicit Conditional Rendering
impact: LOW
impactDescription: prevents rendering 0 or NaN
tags: rendering, conditional, jsx, falsy-values
---
## Use Explicit Conditional Rendering
Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
**Incorrect (renders "0" when count is 0):**
```tsx
function Badge({ count }: { count: number }) {
return (
<div>
{count && <span className="badge">{count}</span>}
</div>
)
}
// When count = 0, renders: <div>0</div>
// When count = 5, renders: <div><span class="badge">5</span></div>
```
**Correct (renders nothing when count is 0):**
```tsx
function Badge({ count }: { count: number }) {
return (
<div>
{count > 0 ? <span className="badge">{count}</span> : null}
</div>
)
}
// When count = 0, renders: <div></div>
// When count = 5, renders: <div><span class="badge">5</span></div>
```
---
title: CSS content-visibility for Long Lists
impact: HIGH
impactDescription: faster initial render
tags: rendering, css, content-visibility, long-lists
---
## CSS content-visibility for Long Lists
Apply `content-visibility: auto` to defer off-screen rendering.
**CSS:**
```css
.message-item {
content-visibility: auto;
contain-intrinsic-size: 0 80px;
}
```
**Example:**
```tsx
function MessageList({ messages }: { messages: Message[] }) {
return (
<div className="overflow-y-auto h-screen">
{messages.map(msg => (
<div key={msg.id} className="message-item">
<Avatar user={msg.author} />
<div>{msg.content}</div>
</div>
))}
</div>
)
}
```
For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
---
title: Hoist Static JSX Elements
impact: LOW
impactDescription: avoids re-creation
tags: rendering, jsx, static, optimization
---
## Hoist Static JSX Elements
Extract static JSX outside components to avoid re-creation.
**Incorrect (recreates element every render):**
```tsx
function LoadingSkeleton() {
return <div className="animate-pulse h-20 bg-gray-200" />
}
function Container() {
return (
<div>
{loading && <LoadingSkeleton />}
</div>
)
}
```
**Correct (reuses same element):**
```tsx
const loadingSkeleton = (
<div className="animate-pulse h-20 bg-gray-200" />
)
function Container() {
return (
<div>
{loading && loadingSkeleton}
</div>
)
}
```
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
---
title: Prevent Hydration Mismatch Without Flickering
impact: MEDIUM
impactDescription: avoids visual flicker and hydration errors
tags: rendering, ssr, hydration, localStorage, flicker
---
## Prevent Hydration Mismatch Without Flickering
When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
**Incorrect (breaks SSR):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
// localStorage is not available on server - throws error
const theme = localStorage.getItem('theme') || 'light'
return (
<div className={theme}>
{children}
</div>
)
}
```
Server-side rendering will fail because `localStorage` is undefined.
**Incorrect (visual flickering):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState('light')
useEffect(() => {
// Runs after hydration - causes visible flash
const stored = localStorage.getItem('theme')
if (stored) {
setTheme(stored)
}
}, [])
return (
<div className={theme}>
{children}
</div>
)
}
```
Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
**Correct (no flicker, no hydration mismatch):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
return (
<>
<div id="theme-wrapper">
{children}
</div>
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
var theme = localStorage.getItem('theme') || 'light';
var el = document.getElementById('theme-wrapper');
if (el) el.className = theme;
} catch (e) {}
})();
`,
}}
/>
</>
)
}
```
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
---
title: Suppress Expected Hydration Mismatches
impact: LOW-MEDIUM
impactDescription: avoids noisy hydration warnings for known differences
tags: rendering, hydration, ssr, nextjs
---
## Suppress Expected Hydration Mismatches
In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.
**Incorrect (known mismatch warnings):**
```tsx
function Timestamp() {
return <span>{new Date().toLocaleString()}</span>
}
```
**Correct (suppress expected mismatch only):**
```tsx
function Timestamp() {
return (
<span suppressHydrationWarning>
{new Date().toLocaleString()}
</span>
)
}
```
---
title: Use React DOM Resource Hints
impact: HIGH
impactDescription: reduces load time for critical resources
tags: rendering, preload, preconnect, prefetch, resource-hints
---
## Use React DOM Resource Hints
**Impact: HIGH (reduces load time for critical resources)**
React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.
- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to
- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server
- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon
- **`preloadModule(href)`**: Fetch an ES module you'll use soon
- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script
- **`preinitModule(href)`**: Fetch and evaluate an ES module
**Example (preconnect to third-party APIs):**
```tsx
import { preconnect, prefetchDNS } from 'react-dom'
export default function App() {
prefetchDNS('https://analytics.example.com')
preconnect('https://api.example.com')
return <main>{/* content */}</main>
}
```
**Example (preload critical fonts and styles):**
```tsx
import { preload, preinit } from 'react-dom'
export default function RootLayout({ children }) {
// Preload font file
preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })
// Fetch and apply critical stylesheet immediately
preinit('/styles/critical.css', { as: 'style' })
return (
<html>
<body>{children}</body>
</html>
)
}
```
**Example (preload modules for code-split routes):**
```tsx
import { preloadModule, preinitModule } from 'react-dom'
function Navigation() {
const preloadDashboard = () => {
preloadModule('/dashboard.js', { as: 'script' })
}
return (
<nav>
<a href="/dashboard" onMouseEnter={preloadDashboard}>
Dashboard
</a>
</nav>
)
}
```
**When to use each:**
| API | Use case |
|-----|----------|
| `prefetchDNS` | Third-party domains you'll connect to later |
| `preconnect` | APIs or CDNs you'll fetch from immediately |
| `preload` | Critical resources needed for current page |
| `preloadModule` | JS modules for likely next navigation |
| `preinit` | Stylesheets/scripts that must execute early |
| `preinitModule` | ES modules that must execute early |
Reference: [React DOM Resource Preloading APIs](https://react.dev/reference/react-dom#resource-preloading-apis)
---
title: Use defer or async on Script Tags
impact: HIGH
impactDescription: eliminates render-blocking
tags: rendering, script, defer, async, performance
---
## Use defer or async on Script Tags
**Impact: HIGH (eliminates render-blocking)**
Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.
- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order
- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order
Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.
**Incorrect (blocks rendering):**
```tsx
export default function Document() {
return (
<html>
<head>
<script src="https://example.com/analytics.js" />
<script src="/scripts/utils.js" />
</head>
<body>{/* content */}</body>
</html>
)
}
```
**Correct (non-blocking):**
```tsx
export default function Document() {
return (
<html>
<head>
{/* Independent script - use async */}
<script src="https://example.com/analytics.js" async />
{/* DOM-dependent script - use defer */}
<script src="/scripts/utils.js" defer />
</head>
<body>{/* content */}</body>
</html>
)
}
```
**Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:
```tsx
import Script from 'next/script'
export default function Page() {
return (
<>
<Script src="https://example.com/analytics.js" strategy="afterInteractive" />
<Script src="/scripts/utils.js" strategy="beforeInteractive" />
</>
)
}
```
Reference: [MDN - Script element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)
---
title: Optimize SVG Precision
impact: LOW
impactDescription: reduces file size
tags: rendering, svg, optimization, svgo
---
## Optimize SVG Precision
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
**Incorrect (excessive precision):**
```svg
<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
```
**Correct (1 decimal place):**
```svg
<path d="M 10.3 20.8 L 30.9 40.2" />
```
**Automate with SVGO:**
```bash
npx svgo --precision=1 --multipass icon.svg
```
---
title: Use useTransition Over Manual Loading States
impact: LOW
impactDescription: reduces re-renders and improves code clarity
tags: rendering, transitions, useTransition, loading, state
---
## Use useTransition Over Manual Loading States
Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.
**Incorrect (manual loading state):**
```tsx
function SearchResults() {
const [query, setQuery] = useState('')
const [results, setResults] = useState([])
const [isLoading, setIsLoading] = useState(false)
const handleSearch = async (value: string) => {
setIsLoading(true)
setQuery(value)
const data = await fetchResults(value)
setResults(data)
setIsLoading(false)
}
return (
<>
<input onChange={(e) => handleSearch(e.target.value)} />
{isLoading && <Spinner />}
<ResultsList results={results} />
</>
)
}
```
**Correct (useTransition with built-in pending state):**
```tsx
import { useTransition, useState } from 'react'
function SearchResults() {
const [query, setQuery] = useState('')
const [results, setResults] = useState([])
const [isPending, startTransition] = useTransition()
const handleSearch = (value: string) => {
setQuery(value) // Update input immediately
startTransition(async () => {
// Fetch and update results
const data = await fetchResults(value)
setResults(data)
})
}
return (
<>
<input onChange={(e) => handleSearch(e.target.value)} />
{isPending && <Spinner />}
<ResultsList results={results} />
</>
)
}
```
**Benefits:**
- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`
- **Error resilience**: Pending state correctly resets even if the transition throws
- **Better responsiveness**: Keeps the UI responsive during updates
- **Interrupt handling**: New transitions automatically cancel pending ones
Reference: [useTransition](https://react.dev/reference/react/useTransition)
---
title: Defer State Reads to Usage Point
impact: MEDIUM
impactDescription: avoids unnecessary subscriptions
tags: rerender, searchParams, localStorage, optimization
---
## Defer State Reads to Usage Point
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 <button onClick={handleShare}>Share</button>
}
```
**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 <button onClick={handleShare}>Share</button>
}
```
---
title: Narrow Effect Dependencies
impact: LOW
impactDescription: minimizes effect re-runs
tags: rerender, useEffect, dependencies, optimization
---
## Narrow Effect Dependencies
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])
```
---
title: Calculate Derived State During Rendering
impact: MEDIUM
impactDescription: avoids redundant renders and state drift
tags: rerender, derived-state, useEffect, state
---
## Calculate Derived State During Rendering
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 <p>{fullName}</p>
}
```
**Correct (derive during render):**
```tsx
function Form() {
const [firstName, setFirstName] = useState('First')
const [lastName, setLastName] = useState('Last')
const fullName = firstName + ' ' + lastName
return <p>{fullName}</p>
}
```
References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
---
title: Subscribe to Derived State
impact: MEDIUM
impactDescription: reduces re-render frequency
tags: rerender, derived-state, media-query, optimization
---
## Subscribe to Derived State
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 <nav className={isMobile ? 'mobile' : 'desktop'} />
}
```
**Correct (re-renders only when boolean changes):**
```tsx
function Sidebar() {
const isMobile = useMediaQuery('(max-width: 767px)')
return <nav className={isMobile ? 'mobile' : 'desktop'} />
}
```
---
title: Use Functional setState Updates
impact: MEDIUM
impactDescription: prevents stale closures and unnecessary callback recreations
tags: react, hooks, useState, useCallback, callbacks, closures
---
## Use Functional setState Updates
When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
**Incorrect (requires state as dependency):**
```tsx
function TodoList() {
const [items, setItems] = useState(initialItems)
// Callback must depend on items, recreated on every items change
const addItems = useCallback((newItems: Item[]) => {
setItems([...items, ...newItems])
}, [items]) // ❌ items dependency causes recreations
// Risk of stale closure if dependency is forgotten
const removeItem = useCallback((id: string) => {
setItems(items.filter(item => item.id !== id))
}, []) // ❌ Missing items dependency - will use stale items!
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
}
```
The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
**Correct (stable callbacks, no stale closures):**
```tsx
function TodoList() {
const [items, setItems] = useState(initialItems)
// Stable callback, never recreated
const addItems = useCallback((newItems: Item[]) => {
setItems(curr => [...curr, ...newItems])
}, []) // ✅ No dependencies needed
// Always uses latest state, no stale closure risk
const removeItem = useCallback((id: string) => {
setItems(curr => curr.filter(item => item.id !== id))
}, []) // ✅ Safe and stable
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
}
```
**Benefits:**
1. **Stable callback references** - Callbacks don't need to be recreated when state changes
2. **No stale closures** - Always operates on the latest state value
3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
4. **Prevents bugs** - Eliminates the most common source of React closure bugs
**When to use functional updates:**
- Any setState that depends on the current state value
- Inside useCallback/useMemo when state is needed
- Event handlers that reference state
- Async operations that update state
**When direct updates are fine:**
- Setting state to a static value: `setCount(0)`
- Setting state from props/arguments only: `setName(newName)`
- State doesn't depend on previous value
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
---
title: Use Lazy State Initialization
impact: MEDIUM
impactDescription: wasted computation on every render
tags: react, hooks, useState, performance, initialization
---
## Use Lazy State Initialization
Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
**Incorrect (runs on every render):**
```tsx
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs on EVERY render, even after initialization
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
const [query, setQuery] = useState('')
// When query changes, buildSearchIndex runs again unnecessarily
return <SearchResults index={searchIndex} query={query} />
}
function UserProfile() {
// JSON.parse runs on every render
const [settings, setSettings] = useState(
JSON.parse(localStorage.getItem('settings') || '{}')
)
return <SettingsForm settings={settings} onChange={setSettings} />
}
```
**Correct (runs only once):**
```tsx
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs ONLY on initial render
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
const [query, setQuery] = useState('')
return <SearchResults index={searchIndex} query={query} />
}
function UserProfile() {
// JSON.parse runs only on initial render
const [settings, setSettings] = useState(() => {
const stored = localStorage.getItem('settings')
return stored ? JSON.parse(stored) : {}
})
return <SettingsForm settings={settings} onChange={setSettings} />
}
```
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
---
title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
impact: MEDIUM
impactDescription: restores memoization by using a constant for default value
tags: rerender, memo, optimization
---
## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
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
<UserAvatar />
```
**Correct (stable default value):**
```tsx
const NOOP = () => {};
const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
// ...
})
// Used without optional onClick
<UserAvatar />
```
---
title: Extract to Memoized Components
impact: MEDIUM
impactDescription: enables early returns
tags: rerender, memo, useMemo, optimization
---
## Extract to Memoized Components
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 <Avatar id={id} />
}, [user])
if (loading) return <Skeleton />
return <div>{avatar}</div>
}
```
**Correct (skips computation when loading):**
```tsx
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
const id = useMemo(() => computeAvatarId(user), [user])
return <Avatar id={id} />
})
function Profile({ user, loading }: Props) {
if (loading) return <Skeleton />
return (
<div>
<UserAvatar user={user} />
</div>
)
}
```
**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.
---
title: Put Interaction Logic in Event Handlers
impact: MEDIUM
impactDescription: avoids effect re-runs and duplicate side effects
tags: rerender, useEffect, events, side-effects, dependencies
---
## Put Interaction Logic in Event Handlers
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 <button onClick={() => setSubmitted(true)}>Submit</button>
}
```
**Correct (do it in the handler):**
```tsx
function Form() {
const theme = useContext(ThemeContext)
function handleSubmit() {
post('/api/register')
showToast('Registered', theme)
}
return <button onClick={handleSubmit}>Submit</button>
}
```
Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
---
title: Don't Define Components Inside Components
impact: HIGH
impactDescription: prevents remount on every render
tags: rerender, components, remount, performance
---
## 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 = () => (
<img
src={user.avatarUrl}
className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}
/>
)
// Defined inside to access `user` - BAD
const Stats = () => (
<div>
<span>{user.followers} followers</span>
<span>{user.posts} posts</span>
</div>
)
return (
<div>
<Avatar />
<Stats />
</div>
)
}
```
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 (
<img
src={src}
className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}
/>
)
}
function Stats({ followers, posts }: { followers: number; posts: number }) {
return (
<div>
<span>{followers} followers</span>
<span>{posts} posts</span>
</div>
)
}
function UserProfile({ user, theme }) {
return (
<div>
<Avatar src={user.avatarUrl} theme={theme} />
<Stats followers={user.followers} posts={user.posts} />
</div>
)
}
```
**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
---
title: Do not wrap a simple expression with a primitive result type in useMemo
impact: LOW-MEDIUM
impactDescription: wasted computation on every render
tags: rerender, useMemo, optimization
---
## Do not wrap a simple expression with a primitive result type in useMemo
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 <Skeleton />
// return some markup
}
```
**Correct:**
```tsx
function Header({ user, notifications }: Props) {
const isLoading = user.isLoading || notifications.isLoading
if (isLoading) return <Skeleton />
// return some markup
}
```
---
title: Split Combined Hook Computations
impact: MEDIUM
impactDescription: avoids recomputing independent steps
tags: rerender, useMemo, useEffect, dependencies, optimization
---
## Split Combined Hook Computations
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.
---
title: Use Transitions for Non-Urgent Updates
impact: MEDIUM
impactDescription: maintains UI responsiveness
tags: rerender, transitions, startTransition, performance
---
## Use Transitions for Non-Urgent Updates
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
**Incorrect (blocks UI on every scroll):**
```tsx
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0)
useEffect(() => {
const handler = () => setScrollY(window.scrollY)
window.addEventListener('scroll', handler, { passive: true })
return () => window.removeEventListener('scroll', handler)
}, [])
}
```
**Correct (non-blocking updates):**
```tsx
import { startTransition } from 'react'
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0)
useEffect(() => {
const handler = () => {
startTransition(() => setScrollY(window.scrollY))
}
window.addEventListener('scroll', handler, { passive: true })
return () => window.removeEventListener('scroll', handler)
}, [])
}
```
---
title: Use useDeferredValue for Expensive Derived Renders
impact: MEDIUM
impactDescription: keeps input responsive during heavy computation
tags: rerender, useDeferredValue, optimization, concurrent
---
## Use useDeferredValue for Expensive Derived Renders
When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.
**Incorrect (input feels laggy while filtering):**
```tsx
function Search({ items }: { items: Item[] }) {
const [query, setQuery] = useState('')
const filtered = items.filter(item => fuzzyMatch(item, query))
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} />
<ResultsList results={filtered} />
</>
)
}
```
**Correct (input stays snappy, results render when ready):**
```tsx
function Search({ items }: { items: Item[] }) {
const [query, setQuery] = useState('')
const deferredQuery = useDeferredValue(query)
const filtered = useMemo(
() => items.filter(item => fuzzyMatch(item, deferredQuery)),
[items, deferredQuery]
)
const isStale = query !== deferredQuery
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} />
<div style={{ opacity: isStale ? 0.7 : 1 }}>
<ResultsList results={filtered} />
</div>
</>
)
}
```
**When to use:**
- Filtering/searching large lists
- Expensive visualizations (charts, graphs) reacting to input
- Any derived state that causes noticeable render delays
**Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.
Reference: [React useDeferredValue](https://react.dev/reference/react/useDeferredValue)
---
title: Use useRef for Transient Values
impact: MEDIUM
impactDescription: avoids unnecessary re-renders on frequent updates
tags: rerender, useref, state, performance
---
## Use useRef for Transient Values
When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
**Incorrect (renders every update):**
```tsx
function Tracker() {
const [lastX, setLastX] = useState(0)
useEffect(() => {
const onMove = (e: MouseEvent) => setLastX(e.clientX)
window.addEventListener('mousemove', onMove)
return () => window.removeEventListener('mousemove', onMove)
}, [])
return (
<div
style={{
position: 'fixed',
top: 0,
left: lastX,
width: 8,
height: 8,
background: 'black',
}}
/>
)
}
```
**Correct (no re-render for tracking):**
```tsx
function Tracker() {
const lastXRef = useRef(0)
const dotRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const onMove = (e: MouseEvent) => {
lastXRef.current = e.clientX
const node = dotRef.current
if (node) {
node.style.transform = `translateX(${e.clientX}px)`
}
}
window.addEventListener('mousemove', onMove)
return () => window.removeEventListener('mousemove', onMove)
}, [])
return (
<div
ref={dotRef}
style={{
position: 'fixed',
top: 0,
left: 0,
width: 8,
height: 8,
background: 'black',
transform: 'translateX(0px)',
}}
/>
)
}
```
---
title: Use after() for Non-Blocking Operations
impact: MEDIUM
impactDescription: faster response times
tags: server, async, logging, analytics, side-effects
---
## Use after() for Non-Blocking Operations
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)
---
title: Authenticate Server Actions Like API Routes
impact: CRITICAL
impactDescription: prevents unauthorized access to server mutations
tags: server, server-actions, authentication, security, authorization
---
## 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)
---
title: Cross-Request LRU Caching
impact: HIGH
impactDescription: caches across requests
tags: server, cache, lru, cross-request
---
## Cross-Request LRU Caching
`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<string, any>({
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)
---
title: Per-Request Deduplication with React.cache()
impact: MEDIUM
impactDescription: deduplicates within request
tags: server, cache, react-cache, deduplication
---
## Per-Request Deduplication with React.cache()
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 getUser = cache(async (uid: number) => {
return await db.user.findUnique({ where: { id: uid } })
})
// Primitive args use value equality
getUser(1)
getUser(1) // Cache hit, returns cached result
```
If you must pass objects, pass the same reference:
```typescript
const params = { uid: 1 }
getUser(params) // Query runs
getUser(params) // Cache hit (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: [React.cache documentation](https://react.dev/reference/react/cache)
---
title: Avoid Duplicate Serialization in RSC Props
impact: LOW
impactDescription: reduces network payload by avoiding duplicate serialization
tags: server, rsc, serialization, props, client-components
---
## 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)
<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
```
**Correct (sends 3 strings):**
```tsx
// RSC: send once
<ClientList usernames={usernames} />
// Client: transform there
'use client'
const sorted = useMemo(() => [...usernames].sort(), [usernames])
```
**Nested deduplication behavior:**
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
```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)
```
**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
<C users={users} active={users.filter(u => u.active)} />
<C product={product} productName={product.name} />
// ✅ Good
<C users={users} />
<C product={product} />
// Do filtering/destructuring in client
```
**Exception:** Pass derived data when transformation is expensive or client doesn't need original.
---
title: Hoist Static I/O to Module Level
impact: HIGH
impactDescription: avoids repeated file/network I/O per request
tags: server, io, performance, next.js, route-handlers, og-image
---
## 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(
<div style={{ fontFamily: 'Inter' }}>
<img src={logoData} />
Hello World
</div>,
{ 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(
<div style={{ fontFamily: 'Inter' }}>
<img src={logo} />
Hello World
</div>,
{ 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(
<div style={{ fontFamily: 'Inter' }}>
<img src={logoData} />
Hello World
</div>,
{ 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.
---
title: Avoid Shared Module State for Request Data
impact: HIGH
impactDescription: prevents concurrency bugs and request data leaks
tags: server, rsc, ssr, concurrency, security, state
---
## Avoid Shared Module State for Request Data
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 <Dashboard />
}
async function Dashboard() {
return <div>{currentUser?.name}</div>
}
```
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 <Dashboard user={user} />
}
function Dashboard({ user }: { user: User | null }) {
return <div>{user?.name}</div>
}
```
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).
---
title: Parallel Data Fetching with Component Composition
impact: CRITICAL
impactDescription: eliminates server-side waterfalls
tags: server, rsc, parallel-fetching, composition
---
## Parallel Data Fetching with Component Composition
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 (
<div>
<div>{header}</div>
<Sidebar />
</div>
)
}
async function Sidebar() {
const items = await fetchSidebarItems()
return <nav>{items.map(renderItem)}</nav>
}
```
**Correct (both fetch simultaneously):**
```tsx
async function Header() {
const data = await fetchHeader()
return <div>{data}</div>
}
async function Sidebar() {
const items = await fetchSidebarItems()
return <nav>{items.map(renderItem)}</nav>
}
export default function Page() {
return (
<div>
<Header />
<Sidebar />
</div>
)
}
```
**Alternative with children prop:**
```tsx
async function Header() {
const data = await fetchHeader()
return <div>{data}</div>
}
async function Sidebar() {
const items = await fetchSidebarItems()
return <nav>{items.map(renderItem)}</nav>
}
function Layout({ children }: { children: ReactNode }) {
return (
<div>
<Header />
{children}
</div>
)
}
export default function Page() {
return (
<Layout>
<Sidebar />
</Layout>
)
}
```
---
title: Parallel Nested Data Fetching
impact: CRITICAL
impactDescription: eliminates server-side waterfalls
tags: server, rsc, parallel-fetching, promise-chaining
---
## Parallel Nested Data Fetching
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.
---
title: Minimize Serialization at RSC Boundaries
impact: HIGH
impactDescription: reduces data transfer size
tags: server, rsc, serialization, props
---
## Minimize Serialization at RSC Boundaries
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 <Profile user={user} />
}
'use client'
function Profile({ user }: { user: User }) {
return <div>{user.name}</div> // uses 1 field
}
```
**Correct (serializes only 1 field):**
```tsx
async function Page() {
const user = await fetchUser()
return <Profile name={user.name} />
}
'use client'
function Profile({ name }: { name: string }) {
return <div>{name}</div>
}
```
# React View Transitions
**Version 1.0.0**
Vercel Engineering
March 2026
> **Note:**
> This document is mainly for agents and LLMs to follow when implementing
> view transitions in React applications. Humans may also find it useful,
> but guidance here is optimized for automation and consistency by
> AI-assisted workflows.
---
## Abstract
Guide for implementing smooth, native-feeling animations using React's View Transition API. Covers the `<ViewTransition>` component, `addTransitionType`, CSS view transition pseudo-elements, shared element transitions, Suspense reveals, list reorder, directional navigation, and Next.js integration. Includes a step-by-step implementation workflow, ready-to-use CSS animation recipes, and common mistake warnings.
---
## Table of Contents
1. [Core Reference](#when-to-animate)
- [When to Animate](#when-to-animate)
- [Availability](#availability)
- [Core Concepts](#core-concepts)
- [Styling with View Transition Classes](#styling-with-view-transition-classes)
- [Transition Types](#transition-types)
- [Shared Element Transitions](#shared-element-transitions)
- [Common Patterns](#common-patterns)
- [How Multiple VTs Interact](#how-multiple-vts-interact)
- [Next.js Integration](#nextjs-integration)
- [Accessibility](#accessibility)
2. [Implementation Workflow](#implementation-workflow)
- [Step 1: Audit the App](#step-1-audit-the-app)
- [Step 2: Add CSS Recipes](#step-2-add-css-recipes)
- [Step 3: Isolate Persistent Elements](#step-3-isolate-persistent-elements)
- [Step 4: Add Directional Page Transitions](#step-4-add-directional-page-transitions)
- [Step 5: Add Suspense Reveals](#step-5-add-suspense-reveals)
- [Step 6: Add Shared Element Transitions](#step-6-add-shared-element-transitions)
- [Step 7: Verify Each Navigation Path](#step-7-verify-each-navigation-path)
- [Common Mistakes](#common-mistakes)
3. [Patterns and Guidelines](#patterns-and-guidelines)
4. [CSS Animation Recipes](#css-animation-recipes)
5. [View Transitions in Next.js](#view-transitions-in-nextjs)
---
Animate between UI states using the browser's native `document.startViewTransition`. Declare *what* with `<ViewTransition>`, trigger *when* with `startTransition` / `useDeferredValue` / `Suspense`, control *how* with CSS classes. Unsupported browsers skip animations gracefully.
## When to Animate
Every `<ViewTransition>` should communicate a spatial relationship or continuity. If you can't articulate what it communicates, don't add it.
Implement **all** applicable patterns from this list, in this order:
| Priority | Pattern | What it communicates |
|----------|---------|---------------------|
| 1 | **Shared element** (`name`) | "Same thing — going deeper" |
| 2 | **Suspense reveal** | "Data loaded" |
| 3 | **List identity** (per-item `key`) | "Same items, new arrangement" |
| 4 | **State change** (`enter`/`exit`) | "Something appeared/disappeared" |
| 5 | **Route change** (layout-level) | "Going to a new place" |
This is an implementation order, not a "pick one" list. Implement every pattern that fits the app. Only skip a pattern if the app has no use case for it.
### Choosing Animation Style
| Context | Animation | Why |
|---------|-----------|-----|
| Hierarchical navigation (list → detail) | Type-keyed `nav-forward` / `nav-back` | Communicates spatial depth |
| Lateral navigation (tab-to-tab) | Bare `<ViewTransition>` (fade) or `default="none"` | No depth to communicate |
| Suspense reveal | `enter`/`exit` string props | Content arriving |
| Revalidation / background refresh | `default="none"` | Silent — no animation needed |
Reserve directional slides for hierarchical navigation (list → detail) and ordered sequences (prev/next photo, carousel, paginated results). For ordered sequences, the direction communicates position: "next" slides from right, "previous" from left. Lateral/unordered navigation (tab-to-tab) should not use directional slides — it falsely implies spatial depth.
---
## Availability
- **Next.js:** Do **not** install `react@canary` — the App Router already bundles React canary internally. `ViewTransition` works out of the box. `npm ls react` may show a stable-looking version; this is expected.
- **Without Next.js:** Install `react@canary react-dom@canary` (`ViewTransition` is not in stable React).
- Browser support: Chromium 111+, Firefox 144+, Safari 18.2+. Graceful degradation.
---
## Core Concepts
### The `<ViewTransition>` Component
```jsx
import { ViewTransition } from 'react';
<ViewTransition>
<Component />
</ViewTransition>
```
React auto-assigns a unique `view-transition-name` and calls `document.startViewTransition` behind the scenes. Never call `startViewTransition` yourself.
### Animation Triggers
| Trigger | When it fires |
|---------|--------------|
| **enter** | VT first inserted during a Transition |
| **exit** | VT first removed during a Transition |
| **update** | DOM mutations inside a VT. With nested VTs, mutation applies to the innermost one |
| **share** | Named VT unmounts and another with same `name` mounts in same Transition |
Only `startTransition`, `useDeferredValue`, or `Suspense` activate VTs. Regular `setState` does not animate.
### Critical Placement Rule
VT only activates enter/exit if it appears **before any DOM nodes**:
```jsx
// Works
<ViewTransition enter="auto" exit="auto"><div>Content</div></ViewTransition>
// Broken — div wraps the VT
<div><ViewTransition enter="auto" exit="auto"><div>Content</div></ViewTransition></div>
```
---
## Styling with View Transition Classes
Values: `"auto"` (browser cross-fade), `"none"` (disabled), `"class-name"` (custom CSS), or `{ [type]: value }` for type-specific animations.
```jsx
<ViewTransition default="none" enter="slide-in" exit="slide-out" share="morph" />
```
If `default` is `"none"`, all triggers are off unless explicitly listed.
### CSS Pseudo-Elements
- `::view-transition-old(.class)` — outgoing snapshot
- `::view-transition-new(.class)` — incoming snapshot
- `::view-transition-group(.class)` — container
- `::view-transition-image-pair(.class)` — old + new pair
---
## Transition Types
Tag transitions with `addTransitionType` so VTs can pick different animations. Call it multiple times to stack types — different VTs in the tree react to different types:
```jsx
startTransition(() => {
addTransitionType('nav-forward');
addTransitionType('select-item');
router.push('/detail/1');
});
```
Map types to CSS classes. Works on `enter`, `exit`, **and** `share`:
```jsx
<ViewTransition
enter={{ 'nav-forward': 'slide-from-right', 'nav-back': 'slide-from-left', default: 'none' }}
exit={{ 'nav-forward': 'slide-to-left', 'nav-back': 'slide-to-right', default: 'none' }}
share={{ 'nav-forward': 'morph-forward', 'nav-back': 'morph-back', default: 'morph' }}
default="none"
>
<Page />
</ViewTransition>
```
`enter` and `exit` don't have to be symmetric. For example, fade in but slide out directionally:
```jsx
<ViewTransition
enter={{ 'nav-forward': 'fade-in', 'nav-back': 'fade-in', default: 'none' }}
exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}
default="none"
>
```
**TypeScript:** `ViewTransitionClassPerType` requires a `default` key.
### `router.back()` and Browser Back Button
`router.back()` and the browser's back/forward buttons do **not** trigger view transitions (`popstate` is synchronous, incompatible with `startViewTransition`). Use `router.push()` with an explicit URL instead.
### Types and Suspense
Types are available during navigation but **not** during subsequent Suspense reveals (separate transitions, no type). Use type maps for page-level enter/exit; use simple string props for Suspense reveals.
---
## Shared Element Transitions
Same `name` on two VTs — one unmounting, one mounting — creates a shared element morph:
```jsx
<ViewTransition name="hero-image">
<img src="/thumb.jpg" onClick={() => startTransition(() => onSelect())} />
</ViewTransition>
// Other view — same name
<ViewTransition name="hero-image">
<img src="/full.jpg" />
</ViewTransition>
```
- Only one VT with a given `name` can be mounted at a time — use unique names. Watch for reusable components: if a component with a named VT is rendered in both a modal/popover *and* a page, both mount simultaneously and break the morph. Either make the name conditional (via a prop) or move the named VT out of the shared component into the specific consumer.
- `share` takes precedence over `enter`/`exit`. Think through each navigation path: when no pair forms, `enter`/`exit` fires instead. Consider whether the element needs a fallback animation for those paths.
- Never use fade-out exit on pages with shared morphs — use directional slide.
---
## Common Patterns
### Enter/Exit
```jsx
{show && (
<ViewTransition enter="fade-in" exit="fade-out"><Panel /></ViewTransition>
)}
```
### List Reorder
```jsx
{items.map(item => (
<ViewTransition key={item.id}><ItemCard item={item} /></ViewTransition>
))}
```
Trigger inside `startTransition`. Avoid wrapper `<div>`s between list and VT.
### Composing Shared Elements with List Identity
Shared elements and list identity are independent concerns — don't confuse one for the other. When a list item contains a shared element, use two nested `<ViewTransition>` boundaries:
```jsx
{items.map(item => (
<ViewTransition key={item.id}> {/* list identity */}
<Link href={`/items/${item.id}`}>
<ViewTransition name={`item-image-${item.id}`} share="morph"> {/* shared element */}
<Image src={item.image} />
</ViewTransition>
<p>{item.name}</p>
</Link>
</ViewTransition>
))}
```
The outer VT handles list reorder/enter. The inner VT handles cross-route shared element morph. Missing either layer means that animation silently doesn't happen.
### Force Re-Enter with `key`
```jsx
<ViewTransition key={searchParams.toString()} enter="slide-up" default="none">
<ResultsGrid />
</ViewTransition>
```
**Caution:** Wrapping `<Suspense>` with key remounts the boundary and refetches.
### Suspense Fallback to Content
Simple cross-fade:
```jsx
<ViewTransition>
<Suspense fallback={<Skeleton />}><Content /></Suspense>
</ViewTransition>
```
Directional reveal:
```jsx
<Suspense fallback={<ViewTransition exit="slide-down"><Skeleton /></ViewTransition>}>
<ViewTransition enter="slide-up" default="none"><Content /></ViewTransition>
</Suspense>
```
---
## How Multiple VTs Interact
Every VT matching the trigger fires simultaneously in a single `document.startViewTransition`. VTs in **different** transitions don't compete.
### Use `default="none"` Liberally
Without it, every VT fires the browser cross-fade on **every** transition. Always use `default="none"` and explicitly enable only desired triggers.
### Two Patterns Coexist
**Pattern A — Directional slides:** Type-keyed VT on each page, fires during navigation.
**Pattern B — Suspense reveals:** Simple string props, fires when data loads (no type).
They coexist because they fire at different moments. `default="none"` on both prevents cross-interference. Always pair `enter` with `exit`. Place directional VTs in page components, not layouts.
### Nested VT Limitation
When a parent VT exits, nested VTs inside it do **not** fire their own enter/exit — only the outermost VT animates. Per-item staggered animations during page navigation are not possible today. See [react#36135](https://github.com/facebook/react/pull/36135) for an experimental opt-in fix.
---
## Next.js Integration
See the [View Transitions in Next.js](#view-transitions-in-nextjs) section below.
---
## Accessibility
Always add reduced motion CSS to your global stylesheet:
```css
@media (prefers-reduced-motion: reduce) {
::view-transition-old(*),
::view-transition-new(*),
::view-transition-group(*) {
animation-duration: 0s !important;
animation-delay: 0s !important;
}
}
```
---
# Implementation Workflow
**Follow these steps in order.** Start with the audit — do not skip it. Copy the CSS recipes from the CSS Recipes section below — do not write your own animation CSS.
## Step 1: Audit the App
Before writing any code, scan the codebase thoroughly. Search for:
- **Every `<Link>` and `router.push`** — open every file that contains one
- **Every `<Suspense>` boundary** — check what its fallback renders
- **Every page/route component** — each needs a VT placement decision
- **Persistent elements** (headers, navbars, sidebars) — need `viewTransitionName` isolation
- **Shared visual elements** on both source and target views
- **Skeleton-to-content control pairs** — if a fallback renders a control that also exists in the real content, both need a matching `viewTransitionName`
Then classify every navigation and produce a navigation map:
```
| Route | Navigates to | Direction | VT pattern |
|-----------------|----------------------|--------------|-----------------------|
| / | /detail/[id] | forward | directional slide |
| /detail/[id] | / | back | directional slide |
| /detail/[id] | /detail/[other] | sequential | directional slide (ordered prev/next) or key+share crossfade |
| /tab/[a] | /tab/[b] | lateral | key+share crossfade |
| (Suspense) | (content loads) | — | slide-up reveal |
```
For each shared element (`name` prop), note where a pair forms and where it doesn't — this determines whether you need `enter`/`exit` as a fallback alongside `share`.
## Step 2: Add CSS Recipes
Copy the **complete** CSS recipe set from the CSS Animation Recipes section below into your global stylesheet. Don't write your own — the recipes handle staggered timing, motion blur, and reduced motion.
## Step 3: Isolate Persistent Elements
```jsx
<header style={{ viewTransitionName: "site-header" }}>...</header>
```
```css
::view-transition-group(site-header) {
animation: none;
z-index: 100;
}
```
For `backdrop-blur`/`backdrop-filter`, use the backdrop-blur workaround instead.
## Step 4: Add Directional Page Transitions
```jsx
startTransition(() => {
addTransitionType('nav-forward');
router.push('/detail/1');
});
```
Wrap each **page component** (not layout) in a type-keyed VT:
```jsx
<ViewTransition
enter={{ "nav-forward": "nav-forward", "nav-back": "nav-back", default: "none" }}
exit={{ "nav-forward": "nav-forward", "nav-back": "nav-back", default: "none" }}
default="none"
>
<div>...page content...</div>
</ViewTransition>
```
Extract into a reusable component so every page doesn't repeat the type map:
```jsx
export function DirectionalTransition({ children }: { children: React.ReactNode }) {
return (
<ViewTransition
enter={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}
exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}
default="none"
>
{children}
</ViewTransition>
);
}
```
**Rules:** Always pair `enter` with `exit`. Always include `default: "none"`. Place in page components, not layouts. Only use directional slides for hierarchical navigation or ordered sequences (prev/next).
## Step 5: Add Suspense Reveals
```jsx
<Suspense fallback={<ViewTransition exit="slide-down"><Skeleton /></ViewTransition>}>
<ViewTransition enter="slide-up" default="none"><AsyncContent /></ViewTransition>
</Suspense>
```
Use `default="none"` on content VT. Use simple string props (not type maps) — Suspense resolves have no type.
## Step 6: Add Shared Element Transitions
```jsx
// Source view
<ViewTransition name={`photo-${photo.id}`} share="morph" default="none">
<Image src={photo.src} ... />
</ViewTransition>
// Target view — same name
<ViewTransition name={`photo-${photo.id}`} share="morph">
<Image src={photo.src} ... />
</ViewTransition>
```
When list items contain shared elements, compose both patterns — two independent layers:
```jsx
{items.map(item => (
<ViewTransition key={item.id}> {/* list identity */}
<Link href={`/detail/${item.id}`}>
<ViewTransition name={`item-${item.id}`} share="morph" default="none"> {/* shared element */}
<Image src={item.image} ... />
</ViewTransition>
</Link>
</ViewTransition>
))}
```
The outer VT handles list reorder/enter. The inner VT handles cross-route shared element morph. Missing either layer means that animation silently doesn't happen.
**Rules:** Names must be globally unique. Add `default="none"` on list-side shared elements.
## Step 7: Verify Each Navigation Path
Walk through every row in the navigation map from Step 1:
- Does the VT mount/unmount, or stay mounted (same-route)?
- For named VTs: does a shared pair form? If not, does `enter`/`exit` provide a fallback?
- Does `default="none"` block an animation you actually want?
- Do persistent elements stay static?
- Do Suspense reveals animate independently from directional navigations?
---
## Common Mistakes
- **Bare VT without `default="none"`** — fires cross-fade on every transition
- **Directional VT in a layout** — layouts persist, enter/exit won't fire on route changes
- **Fade-out exit with shared morphs** — conflicts with morph, use directional slide
- **Writing custom animation CSS** — use the recipes
- **Missing `default: "none"` in type-keyed objects** — TypeScript requires it, fallback is `"auto"`
- **Type maps on Suspense reveals** — Suspense resolves have no type, use string props
- **Raw `viewTransitionName` CSS to trigger animations** — React only starts view transitions when `<ViewTransition>` components are in the tree. Bare `viewTransitionName` is for isolating elements, not triggering animations.
- **`update` trigger for same-route navigations** — nested VTs steal the mutation from the parent. Use `key` + `name` + `share` instead.
- **Named VT in a reusable component** — if a component with a named VT is rendered in both a modal/popover *and* a page, both mount simultaneously and break the morph. Make the name conditional or move it to the specific consumer.
- **`router.back()` for back navigation**`router.back()` triggers synchronous `popstate`, incompatible with view transitions. Use `router.push()` with an explicit URL.
For Next.js-specific steps, see the Next.js section below.
---
# Patterns and Guidelines
## Searchable Grid with `useDeferredValue`
```tsx
'use client';
import { useDeferredValue, useState, ViewTransition, Suspense } from 'react';
export default function SearchableGrid({ itemsPromise }) {
const [search, setSearch] = useState('');
const deferredSearch = useDeferredValue(search);
return (
<>
<input value={search} onChange={(e) => setSearch(e.currentTarget.value)} />
<ViewTransition>
<Suspense fallback={<GridSkeleton />}>
<ItemGrid itemsPromise={itemsPromise} search={deferredSearch} />
</Suspense>
</ViewTransition>
</>
);
}
```
Per-item named VTs in deferred lists trigger cross-fades on every keystroke. Fix with `default="none"`.
## Card Expand/Collapse with `startTransition`
```tsx
'use client';
import { useState, useRef, startTransition, ViewTransition } from 'react';
export default function ItemGrid({ items }) {
const [expandedId, setExpandedId] = useState(null);
const scrollRef = useRef(0);
return expandedId ? (
<ViewTransition enter="slide-in" name={`item-${expandedId}`}>
<ItemDetail
item={items.find(i => i.id === expandedId)}
onClose={() => {
startTransition(() => {
setExpandedId(null);
setTimeout(() => window.scrollTo({ behavior: 'smooth', top: scrollRef.current }), 100);
});
}}
/>
</ViewTransition>
) : (
<div className="grid grid-cols-3 gap-4">
{items.map(item => (
<ViewTransition key={item.id} name={`item-${item.id}`}>
<ItemCard
item={item}
onSelect={() => {
scrollRef.current = window.scrollY;
startTransition(() => setExpandedId(item.id));
}}
/>
</ViewTransition>
))}
</div>
);
}
```
## Cross-Fade Without Remount
Omit `key` to trigger update (cross-fade) instead of exit + enter. Avoids Suspense remount:
```jsx
<ViewTransition><TabPanel tab={activeTab} /></ViewTransition>
```
## Isolate Elements from Parent Animations
Persistent elements get captured in page's transition snapshot. Fix with `viewTransitionName`:
```jsx
<nav style={{ viewTransitionName: "persistent-nav" }}>{/* ... */}</nav>
```
```css
::view-transition-group(persistent-nav) { animation: none; z-index: 100; }
```
Same for floating elements (popovers, tooltips). Global fix: `::view-transition-group(*) { z-index: 100; }`
## Shared Controls Between Skeleton and Content
Give matching controls the same `viewTransitionName`. Don't put manual `viewTransitionName` on root DOM node inside `<ViewTransition>`.
## Reusable Animated Collapse
```jsx
function AnimatedCollapse({ open, children }) {
if (!open) return null;
return <ViewTransition enter="expand-in" exit="collapse-out">{children}</ViewTransition>;
}
```
## Preserve State with Activity
```jsx
<Activity mode={isVisible ? 'visible' : 'hidden'}>
<ViewTransition enter="slide-in" exit="slide-out"><Sidebar /></ViewTransition>
</Activity>
```
## Exclude Elements with `useOptimistic`
`useOptimistic` values update before snapshot, excluding them from animation. Use for controls; use committed state for animated content.
---
## View Transition Events
Imperative control via `onEnter`, `onExit`, `onUpdate`, `onShare`. Always return cleanup. `onShare` takes precedence.
```jsx
<ViewTransition
onEnter={(instance, types) => {
const anim = instance.new.animate(
[{ transform: 'scale(0.8)', opacity: 0 }, { transform: 'scale(1)', opacity: 1 }],
{ duration: 300, easing: 'ease-out' }
);
return () => anim.cancel();
}}
>
<Component />
</ViewTransition>
```
`instance`: `.old`, `.new`, `.group`, `.imagePair`, `.name`
---
## Animation Timing
| Interaction | Duration |
|------------|----------|
| Direct toggle | 100–200ms |
| Route transition | 150–250ms |
| Suspense reveal | 200–400ms |
| Shared element morph | 300–500ms |
---
## Troubleshooting
**VT not activating:** Ensure VT comes before any DOM node. Ensure `startTransition`.
**"Two VTs with same name":** Names must be globally unique. Use IDs.
**`router.back()` and browser back/forward skip animation:** Use `router.push()` with an explicit URL instead.
**Only updates animate:** Without `<Suspense>`, React treats swaps as updates. Conditionally render the VT itself, or wrap in `<Suspense>`.
**Layout VT prevents page VTs from animating:** Nested VTs never fire enter/exit inside a parent VT. If your layout has a VT wrapping `{children}`, page-level enter/exit will silently not work. Remove the layout VT.
**TS error "Property 'default' is missing":** Type-keyed objects require a `default` key.
**Backdrop-blur flickers:** `::view-transition-old(name) { display: none }` + `::view-transition-new(name) { animation: none }`.
**`border-radius` lost:** Apply `border-radius` directly to captured element.
**Batching:** Multiple updates during animation are batched (A→B→C→D becomes B→D).
---
# CSS Animation Recipes
Ready-to-use CSS for `<ViewTransition>` props. Copy into global stylesheet.
## Timing Variables
```css
:root {
--duration-exit: 150ms;
--duration-enter: 210ms;
--duration-move: 400ms;
}
```
### Shared Keyframes
```css
@keyframes fade {
from { filter: blur(3px); opacity: 0; }
to { filter: blur(0); opacity: 1; }
}
@keyframes slide {
from { translate: var(--slide-offset); }
to { translate: 0; }
}
@keyframes slide-y {
from { transform: translateY(var(--slide-y-offset, 10px)); }
to { transform: translateY(0); }
}
```
## Fade
```css
::view-transition-old(.fade-out) {
animation: var(--duration-exit) ease-in fade reverse;
}
::view-transition-new(.fade-in) {
animation: var(--duration-enter) ease-out var(--duration-exit) both fade;
}
```
## Slide (Vertical)
```css
::view-transition-old(.slide-down) {
animation:
var(--duration-exit) ease-out both fade reverse,
var(--duration-exit) ease-out both slide-y reverse;
}
::view-transition-new(.slide-up) {
animation:
var(--duration-enter) ease-in var(--duration-exit) both fade,
var(--duration-move) ease-in both slide-y;
}
```
## Directional Navigation
### Single-Class Approach
```css
::view-transition-old(.nav-forward) {
--slide-offset: -60px;
animation:
var(--duration-exit) ease-in both fade reverse,
var(--duration-move) ease-in-out both slide reverse;
}
::view-transition-new(.nav-forward) {
--slide-offset: 60px;
animation:
var(--duration-enter) ease-out var(--duration-exit) both fade,
var(--duration-move) ease-in-out both slide;
}
::view-transition-old(.nav-back) {
--slide-offset: 60px;
animation:
var(--duration-exit) ease-in both fade reverse,
var(--duration-move) ease-in-out both slide reverse;
}
::view-transition-new(.nav-back) {
--slide-offset: -60px;
animation:
var(--duration-enter) ease-out var(--duration-exit) both fade,
var(--duration-move) ease-in-out both slide;
}
```
### Separate Enter/Exit Classes
```css
::view-transition-new(.slide-from-right) {
--slide-offset: 60px;
animation:
var(--duration-enter) ease-out var(--duration-exit) both fade,
var(--duration-move) ease-in-out both slide;
}
::view-transition-old(.slide-to-left) {
--slide-offset: -60px;
animation:
var(--duration-exit) ease-in both fade reverse,
var(--duration-move) ease-in-out both slide reverse;
}
::view-transition-new(.slide-from-left) {
--slide-offset: -60px;
animation:
var(--duration-enter) ease-out var(--duration-exit) both fade,
var(--duration-move) ease-in-out both slide;
}
::view-transition-old(.slide-to-right) {
--slide-offset: 60px;
animation:
var(--duration-exit) ease-in both fade reverse,
var(--duration-move) ease-in-out both slide reverse;
}
```
## Shared Element Morph
```css
::view-transition-group(.morph) {
animation-duration: var(--duration-move);
}
::view-transition-image-pair(.morph) {
animation-name: via-blur;
}
@keyframes via-blur {
30% { filter: blur(3px); }
}
```
**Note:** Shared element transitions take raster snapshots. For text with significant size differences (e.g., `<h3>``<h1>`), the old snapshot gets scaled up, producing a visible ghost artifact. Use `text-morph` for text shared elements.
## Text Morph
Avoids raster scaling artifacts on text by hiding the old snapshot and showing the new text at full resolution:
```css
::view-transition-group(.text-morph) {
animation-duration: var(--duration-move);
}
::view-transition-old(.text-morph) {
display: none;
}
::view-transition-new(.text-morph) {
animation: none;
object-fit: none;
object-position: left top;
}
```
## Scale
```css
::view-transition-old(.scale-out) {
animation: var(--duration-exit) ease-in scale-down;
}
::view-transition-new(.scale-in) {
animation: var(--duration-enter) ease-out var(--duration-exit) both scale-up;
}
@keyframes scale-down {
from { transform: scale(1); opacity: 1; }
to { transform: scale(0.85); opacity: 0; }
}
@keyframes scale-up {
from { transform: scale(0.85); opacity: 0; }
to { transform: scale(1); opacity: 1; }
}
```
## Persistent Element Isolation
```css
::view-transition-group(persistent-nav) {
animation: none;
z-index: 100;
}
```
### Backdrop-Blur Workaround
```css
::view-transition-old(persistent-nav) { display: none; }
::view-transition-new(persistent-nav) { animation: none; }
```
## Reduced Motion
```css
@media (prefers-reduced-motion: reduce) {
::view-transition-old(*),
::view-transition-new(*),
::view-transition-group(*) {
animation-duration: 0s !important;
animation-delay: 0s !important;
}
}
```
---
# View Transitions in Next.js
## Setup
```js
// next.config.js
experimental: { viewTransition: true }
```
Wraps every `<Link>` navigation in `document.startViewTransition`. Use `default="none"` to prevent competing animations. Do **not** install `react@canary` — the App Router already bundles it.
## Next.js Implementation Additions
**After Step 2:** Enable the experimental flag.
**Step 4:** Use `transitionTypes` on `<Link>` (if available — see availability note below):
```tsx
<Link href="/photo/1" transitionTypes={["nav-forward"]}>View</Link>
<Link href="/" transitionTypes={["nav-back"]}>Back</Link>
```
**After Step 6:** For same-route dynamic segments, use `key` + `name` + `share` pattern.
## Layout-Level ViewTransition
Don't add a layout-level VT wrapping `{children}` if pages have their own VTs — nested VTs never fire enter/exit inside a parent VT, so page-level enter/exit will silently not work. Remove the layout VT entirely. A bare VT in layout works only if pages have no VTs of their own. Layouts persist across navigations — don't use type-keyed maps in layouts.
## The `transitionTypes` Prop
Works in Server Components, no wrapper needed:
```tsx
<Link href="/products/1" transitionTypes={['nav-forward']}>View</Link>
```
**Availability:** Requires `experimental.viewTransition: true`. Available in Next.js 15+ canary builds and Next.js 16+. If unavailable, use `startTransition` + `addTransitionType` + `router.push()`. To check: `grep -r "transitionTypes" node_modules/next/dist/`. Reserve manual `startTransition` for non-link interactions.
## `loading.tsx` as Suspense Boundary
Next.js `loading.tsx` files are implicit `<Suspense>` boundaries. Wrap the skeleton in `<ViewTransition exit="...">` in `loading.tsx`, and the content in `<ViewTransition enter="..." default="none">` in the page. This is the Next.js-idiomatic equivalent of explicit `<Suspense fallback={...}>`. Same rules apply: use simple string props (not type maps) since Suspense reveals fire without transition types.
## Server-Side Filtering with `router.replace`
For search/sort/filter that re-renders on the server (via URL params), use `startTransition` + `router.replace`. VTs activate because the update is inside `startTransition`. List items wrapped in `<ViewTransition key={item.id}>` animate reorder. This is the server-component alternative to the client-side `useDeferredValue` pattern.
## Two-Layer Pattern (Directional + Suspense)
Directional slides + Suspense reveals coexist because they fire at different moments. Place the directional VT in the **page component** (not layout):
```tsx
<ViewTransition
enter={{ "nav-forward": "slide-from-right", default: "none" }}
exit={{ "nav-forward": "slide-to-left", default: "none" }}
default="none"
>
<div>
<Suspense fallback={<ViewTransition exit="slide-down"><Skeleton /></ViewTransition>}>
<ViewTransition enter="slide-up" default="none"><Content /></ViewTransition>
</Suspense>
</div>
</ViewTransition>
```
## Shared Elements Across Routes
```tsx
// List page
<Link href={`/products/${product.id}`} transitionTypes={['nav-forward']}>
<ViewTransition name={`product-${product.id}`}>
<Image src={product.image} alt={product.name} width={400} height={300} />
</ViewTransition>
</Link>
// Detail page — same name
<ViewTransition name={`product-${product.id}`}>
<Image src={product.image} alt={product.name} width={800} height={600} />
</ViewTransition>
```
## Same-Route Dynamic Segment Transitions
Page stays mounted on dynamic segment change — enter/exit never fire. Use `key` + `name` + `share`:
```tsx
<Suspense fallback={<Skeleton />}>
<ViewTransition key={slug} name={`collection-${slug}`} share="auto" default="none">
<Content slug={slug} />
</ViewTransition>
</Suspense>
```
## Server Components
- `<ViewTransition>` works in Server and Client Components
- `<Link transitionTypes>` works in Server Components
- `addTransitionType` and programmatic nav require Client Components
# React View Transitions Skill
An agent skill for implementing smooth, native-feeling animations using React's View Transition API.
## What This Skill Covers
- **`<ViewTransition>` component** — animation triggers (enter, exit, update, share), placement rules, View Transition Classes
- **`addTransitionType`** — tagging transitions for directional or context-specific animations
- **Shared element transitions** — morphing elements across different views
- **View Transition Events** — imperative JavaScript animations via the Web Animations API
- **CSS pseudo-elements**`::view-transition-old`, `::view-transition-new`, `::view-transition-group`
- **Next.js integration**`experimental.viewTransition`, the `transitionTypes` prop on `next/link`, App Router patterns
- **Accessibility**`prefers-reduced-motion` handling
- **Ready-to-use CSS recipes** — fade, slide, scale, directional navigation
## Skill Structure
```
react-view-transitions/
├── SKILL.md # Core skill (always loaded)
├── AGENTS.md # Full compiled document (all references expanded)
└── references/
├── implementation.md # Step-by-step implementation workflow
├── patterns.md # Real-world patterns, events API, troubleshooting
├── nextjs.md # Next.js-specific patterns
└── css-recipes.md # Copy-paste CSS animations
```
## Installation
Install via [skills.sh](https://skills.sh):
```bash
npx skills install https://github.com/vercel-labs/react-view-transitions-skill
```
## Resources
- [React `<ViewTransition>` docs](https://react.dev/reference/react/ViewTransition)
- [React `addTransitionType` docs](https://react.dev/reference/react/addTransitionType)
- [Next.js `viewTransition` config](https://nextjs.org/docs/app/api-reference/config/next-config-js/viewTransition)
- [Next.js App Router Playground (view transitions)](https://github.com/vercel/next-app-router-playground/tree/main/app/view-transitions) — Vercel's reference implementation
---
name: vercel-react-view-transitions
description: Guide for implementing smooth, native-feeling animations using React's View Transition API (`<ViewTransition>` component, `addTransitionType`, and CSS view transition pseudo-elements). Use this skill whenever the user wants to add page transitions, animate route changes, create shared element animations, animate enter/exit of components, animate list reorder, implement directional (forward/back) navigation animations, or integrate view transitions in Next.js. Also use when the user mentions view transitions, `startViewTransition`, `ViewTransition`, transition types, or asks about animating between UI states in React without third-party animation libraries.
license: MIT
metadata:
author: vercel
version: "1.0.0"
---
# React View Transitions
Animate between UI states using the browser's native `document.startViewTransition`. Declare *what* with `<ViewTransition>`, trigger *when* with `startTransition` / `useDeferredValue` / `Suspense`, control *how* with CSS classes. Unsupported browsers skip animations gracefully.
## When to Animate
Every `<ViewTransition>` should communicate a spatial relationship or continuity. If you can't articulate what it communicates, don't add it.
Implement **all** applicable patterns from this list, in this order:
| Priority | Pattern | What it communicates |
|----------|---------|---------------------|
| 1 | **Shared element** (`name`) | "Same thing — going deeper" |
| 2 | **Suspense reveal** | "Data loaded" |
| 3 | **List identity** (per-item `key`) | "Same items, new arrangement" |
| 4 | **State change** (`enter`/`exit`) | "Something appeared/disappeared" |
| 5 | **Route change** (layout-level) | "Going to a new place" |
This is an implementation order, not a "pick one" list. Implement every pattern that fits the app. Only skip a pattern if the app has no use case for it.
### Choosing Animation Style
| Context | Animation | Why |
|---------|-----------|-----|
| Hierarchical navigation (list → detail) | Type-keyed `nav-forward` / `nav-back` | Communicates spatial depth |
| Lateral navigation (tab-to-tab) | Bare `<ViewTransition>` (fade) or `default="none"` | No depth to communicate |
| Suspense reveal | `enter`/`exit` string props | Content arriving |
| Revalidation / background refresh | `default="none"` | Silent — no animation needed |
Reserve directional slides for hierarchical navigation (list → detail) and ordered sequences (prev/next photo, carousel, paginated results). For ordered sequences, the direction communicates position: "next" slides from right, "previous" from left. Lateral/unordered navigation (tab-to-tab) should not use directional slides — it falsely implies spatial depth.
---
## Availability
- **Next.js:** Do **not** install `react@canary` — the App Router already bundles React canary internally. `ViewTransition` works out of the box. `npm ls react` may show a stable-looking version; this is expected.
- **Without Next.js:** Install `react@canary react-dom@canary` (`ViewTransition` is not in stable React).
- Browser support: Chromium 111+, Firefox 144+, Safari 18.2+. Graceful degradation on unsupported browsers.
---
## Implementation Workflow
When adding view transitions to an existing app, **follow `references/implementation.md` step by step.** Start with the audit — do not skip it. Copy the CSS recipes from `references/css-recipes.md` into the global stylesheet — do not write your own animation CSS.
---
## Core Concepts
### The `<ViewTransition>` Component
```jsx
import { ViewTransition } from 'react';
<ViewTransition>
<Component />
</ViewTransition>
```
React auto-assigns a unique `view-transition-name` and calls `document.startViewTransition` behind the scenes. Never call `startViewTransition` yourself.
### Animation Triggers
| Trigger | When it fires |
|---------|--------------|
| **enter** | `<ViewTransition>` first inserted during a Transition |
| **exit** | `<ViewTransition>` first removed during a Transition |
| **update** | DOM mutations inside a `<ViewTransition>`. With nested VTs, mutation applies to the innermost one |
| **share** | Named VT unmounts and another with same `name` mounts in the same Transition |
Only `startTransition`, `useDeferredValue`, or `Suspense` activate VTs. Regular `setState` does not animate.
### Critical Placement Rule
`<ViewTransition>` only activates enter/exit if it appears **before any DOM nodes**:
```jsx
// Works
<ViewTransition enter="auto" exit="auto">
<div>Content</div>
</ViewTransition>
// Broken — div wraps the VT, suppressing enter/exit
<div>
<ViewTransition enter="auto" exit="auto">
<div>Content</div>
</ViewTransition>
</div>
```
---
## Styling with View Transition Classes
### Props
Values: `"auto"` (browser cross-fade), `"none"` (disabled), `"class-name"` (custom CSS), or `{ [type]: value }` for type-specific animations.
```jsx
<ViewTransition default="none" enter="slide-in" exit="slide-out" share="morph" />
```
If `default` is `"none"`, all triggers are off unless explicitly listed.
### CSS Pseudo-Elements
- `::view-transition-old(.class)` — outgoing snapshot
- `::view-transition-new(.class)` — incoming snapshot
- `::view-transition-group(.class)` — container
- `::view-transition-image-pair(.class)` — old + new pair
See `references/css-recipes.md` for ready-to-use animation recipes.
---
## Transition Types
Tag transitions with `addTransitionType` so VTs can pick different animations based on context. Call it multiple times to stack types — different VTs in the tree react to different types:
```jsx
startTransition(() => {
addTransitionType('nav-forward');
addTransitionType('select-item');
router.push('/detail/1');
});
```
Pass an object to map types to CSS classes. Works on `enter`, `exit`, **and** `share`:
```jsx
<ViewTransition
enter={{ 'nav-forward': 'slide-from-right', 'nav-back': 'slide-from-left', default: 'none' }}
exit={{ 'nav-forward': 'slide-to-left', 'nav-back': 'slide-to-right', default: 'none' }}
share={{ 'nav-forward': 'morph-forward', 'nav-back': 'morph-back', default: 'morph' }}
default="none"
>
<Page />
</ViewTransition>
```
`enter` and `exit` don't have to be symmetric. For example, fade in but slide out directionally:
```jsx
<ViewTransition
enter={{ 'nav-forward': 'fade-in', 'nav-back': 'fade-in', default: 'none' }}
exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}
default="none"
>
```
**TypeScript:** `ViewTransitionClassPerType` requires a `default` key in the object.
For apps with multiple pages, extract the type-keyed VT into a reusable wrapper:
```jsx
export function DirectionalTransition({ children }: { children: React.ReactNode }) {
return (
<ViewTransition
enter={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}
exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}
default="none"
>
{children}
</ViewTransition>
);
}
```
### `router.back()` and Browser Back Button
`router.back()` and the browser's back/forward buttons do **not** trigger view transitions (`popstate` is synchronous, incompatible with `startViewTransition`). Use `router.push()` with an explicit URL instead.
### Types and Suspense
Types are available during navigation but **not** during subsequent Suspense reveals (separate transitions, no type). Use type maps for page-level enter/exit; use simple string props for Suspense reveals.
---
## Shared Element Transitions
Same `name` on two VTs — one unmounting, one mounting — creates a shared element morph:
```jsx
<ViewTransition name="hero-image">
<img src="/thumb.jpg" onClick={() => startTransition(() => onSelect())} />
</ViewTransition>
// On the other view — same name
<ViewTransition name="hero-image">
<img src="/full.jpg" />
</ViewTransition>
```
- Only one VT with a given `name` can be mounted at a time — use unique names (`photo-${id}`). Watch for reusable components: if a component with a named VT is rendered in both a modal/popover *and* a page, both mount simultaneously and break the morph. Either make the name conditional (via a prop) or move the named VT out of the shared component into the specific consumer.
- `share` takes precedence over `enter`/`exit`. Think through each navigation path: when no matching pair forms (e.g., the target page doesn't have the same name), `enter`/`exit` fires instead. Consider whether the element needs a fallback animation for those paths.
- Never use a fade-out exit on pages with shared morphs — use a directional slide instead.
---
## Common Patterns
### Enter/Exit
```jsx
{show && (
<ViewTransition enter="fade-in" exit="fade-out"><Panel /></ViewTransition>
)}
```
### List Reorder
```jsx
{items.map(item => (
<ViewTransition key={item.id}><ItemCard item={item} /></ViewTransition>
))}
```
Trigger inside `startTransition`. Avoid wrapper `<div>`s between list and VT.
### Composing Shared Elements with List Identity
Shared elements and list identity are independent concerns — don't confuse one for the other. When a list item contains a shared element (e.g., an image that morphs into a detail view), use two nested `<ViewTransition>` boundaries:
```jsx
{items.map(item => (
<ViewTransition key={item.id}> {/* list identity */}
<Link href={`/items/${item.id}`}>
<ViewTransition name={`item-image-${item.id}`} share="morph"> {/* shared element */}
<Image src={item.image} />
</ViewTransition>
<p>{item.name}</p>
</Link>
</ViewTransition>
))}
```
The outer VT handles list reorder/enter animations. The inner VT handles the cross-route shared element morph. Missing either layer means that animation silently doesn't happen.
### Force Re-Enter with `key`
```jsx
<ViewTransition key={searchParams.toString()} enter="slide-up" default="none">
<ResultsGrid />
</ViewTransition>
```
**Caution:** If wrapping `<Suspense>`, changing `key` remounts the boundary and refetches.
### Suspense Fallback to Content
Simple cross-fade:
```jsx
<ViewTransition>
<Suspense fallback={<Skeleton />}><Content /></Suspense>
</ViewTransition>
```
Directional reveal:
```jsx
<Suspense fallback={<ViewTransition exit="slide-down"><Skeleton /></ViewTransition>}>
<ViewTransition enter="slide-up" default="none"><Content /></ViewTransition>
</Suspense>
```
For more patterns, see `references/patterns.md`.
---
## How Multiple VTs Interact
Every VT matching the trigger fires simultaneously in a single `document.startViewTransition`. VTs in **different** transitions (navigation vs later Suspense resolve) don't compete.
### Use `default="none"` Liberally
Without it, every VT fires the browser cross-fade on **every** transition — Suspense resolves, `useDeferredValue` updates, background revalidations. Always use `default="none"` and explicitly enable only desired triggers.
### Two Patterns Coexist
**Pattern A — Directional slides:** Type-keyed VT on each page, fires during navigation.
**Pattern B — Suspense reveals:** Simple string props, fires when data loads (no type).
They coexist because they fire at different moments. `default="none"` on both prevents cross-interference. Always pair `enter` with `exit`. Place directional VTs in page components, not layouts.
### Nested VT Limitation
When a parent VT exits, nested VTs inside it do **not** fire their own enter/exit — only the outermost VT animates. Per-item staggered animations during page navigation are not possible today. See [react#36135](https://github.com/facebook/react/pull/36135) for an experimental opt-in fix.
---
## Next.js Integration
For Next.js setup (`experimental.viewTransition` flag, `transitionTypes` prop on `next/link`, App Router patterns, Server Components), see `references/nextjs.md`.
---
## Accessibility
Always add the reduced motion CSS from `references/css-recipes.md` to your global stylesheet.
---
## Reference Files
- **`references/implementation.md`** — Step-by-step implementation workflow.
- **`references/patterns.md`** — Patterns, animation timing, events API, troubleshooting.
- **`references/css-recipes.md`** — Ready-to-use CSS animation recipes.
- **`references/nextjs.md`** — Next.js App Router patterns and Server Component details.
## Full Compiled Document
For the complete guide with all reference files expanded: `AGENTS.md`
{
"version": "1.0.0",
"organization": "Vercel Engineering",
"date": "March 2026",
"abstract": "Guide for implementing smooth, native-feeling animations using React's View Transition API. Covers the <ViewTransition> component, addTransitionType, CSS view transition pseudo-elements, shared element transitions, JavaScript animations via Web Animations API, and Next.js integration including the transitionTypes prop on next/link. Includes ready-to-use CSS animation recipes and real-world patterns from production Next.js apps.",
"references": [
"https://react.dev/reference/react/ViewTransition",
"https://react.dev/reference/react/addTransitionType",
"https://nextjs.org/docs/app/api-reference/config/next-config-js/viewTransition",
"https://github.com/vercel/next-app-router-playground/tree/main/app/view-transitions"
]
}
# CSS Animation Recipes
Ready-to-use CSS for `<ViewTransition>` props. Copy into your global stylesheet.
---
## Timing Variables
```css
:root {
--duration-exit: 150ms;
--duration-enter: 210ms;
--duration-move: 400ms;
}
```
### Shared Keyframes
```css
@keyframes fade {
from { filter: blur(3px); opacity: 0; }
to { filter: blur(0); opacity: 1; }
}
@keyframes slide {
from { translate: var(--slide-offset); }
to { translate: 0; }
}
@keyframes slide-y {
from { transform: translateY(var(--slide-y-offset, 10px)); }
to { transform: translateY(0); }
}
```
---
## Fade
```css
::view-transition-old(.fade-out) {
animation: var(--duration-exit) ease-in fade reverse;
}
::view-transition-new(.fade-in) {
animation: var(--duration-enter) ease-out var(--duration-exit) both fade;
}
```
Usage: `<ViewTransition enter="fade-in" exit="fade-out" />`
---
## Slide (Vertical)
```css
::view-transition-old(.slide-down) {
animation:
var(--duration-exit) ease-out both fade reverse,
var(--duration-exit) ease-out both slide-y reverse;
}
::view-transition-new(.slide-up) {
animation:
var(--duration-enter) ease-in var(--duration-exit) both fade,
var(--duration-move) ease-in both slide-y;
}
```
Usage:
```jsx
<Suspense fallback={<ViewTransition exit="slide-down"><Skeleton /></ViewTransition>}>
<ViewTransition default="none" enter="slide-up"><Content /></ViewTransition>
</Suspense>
```
---
## Directional Navigation
### Separate Enter/Exit Classes
```css
::view-transition-new(.slide-from-right) {
--slide-offset: 60px;
animation:
var(--duration-enter) ease-out var(--duration-exit) both fade,
var(--duration-move) ease-in-out both slide;
}
::view-transition-old(.slide-to-left) {
--slide-offset: -60px;
animation:
var(--duration-exit) ease-in both fade reverse,
var(--duration-move) ease-in-out both slide reverse;
}
::view-transition-new(.slide-from-left) {
--slide-offset: -60px;
animation:
var(--duration-enter) ease-out var(--duration-exit) both fade,
var(--duration-move) ease-in-out both slide;
}
::view-transition-old(.slide-to-right) {
--slide-offset: 60px;
animation:
var(--duration-exit) ease-in both fade reverse,
var(--duration-move) ease-in-out both slide reverse;
}
```
### Single-Class Approach
```css
::view-transition-old(.nav-forward) {
--slide-offset: -60px;
animation:
var(--duration-exit) ease-in both fade reverse,
var(--duration-move) ease-in-out both slide reverse;
}
::view-transition-new(.nav-forward) {
--slide-offset: 60px;
animation:
var(--duration-enter) ease-out var(--duration-exit) both fade,
var(--duration-move) ease-in-out both slide;
}
::view-transition-old(.nav-back) {
--slide-offset: 60px;
animation:
var(--duration-exit) ease-in both fade reverse,
var(--duration-move) ease-in-out both slide reverse;
}
::view-transition-new(.nav-back) {
--slide-offset: -60px;
animation:
var(--duration-enter) ease-out var(--duration-exit) both fade,
var(--duration-move) ease-in-out both slide;
}
```
---
## Shared Element Morph
```css
::view-transition-group(.morph) {
animation-duration: var(--duration-move);
}
::view-transition-image-pair(.morph) {
animation-name: via-blur;
}
@keyframes via-blur {
30% { filter: blur(3px); }
}
```
Usage: `<ViewTransition name={`product-${id}`} share="morph" />`
**Note:** Shared element transitions take raster snapshots. For text with significant size differences (e.g., `<h3>``<h1>`), the old snapshot gets scaled up, producing a visible ghost artifact. Use `text-morph` for text shared elements.
## Text Morph
Avoids raster scaling artifacts on text by hiding the old snapshot and showing the new text at full resolution:
```css
::view-transition-group(.text-morph) {
animation-duration: var(--duration-move);
}
::view-transition-old(.text-morph) {
display: none;
}
::view-transition-new(.text-morph) {
animation: none;
object-fit: none;
object-position: left top;
}
```
Usage: `<ViewTransition name={`title-${id}`} share="text-morph" />`
---
## Scale
```css
::view-transition-old(.scale-out) {
animation: var(--duration-exit) ease-in scale-down;
}
::view-transition-new(.scale-in) {
animation: var(--duration-enter) ease-out var(--duration-exit) both scale-up;
}
@keyframes scale-down {
from { transform: scale(1); opacity: 1; }
to { transform: scale(0.85); opacity: 0; }
}
@keyframes scale-up {
from { transform: scale(0.85); opacity: 0; }
to { transform: scale(1); opacity: 1; }
}
```
Usage: `<ViewTransition enter="scale-in" exit="scale-out" />`
---
## Persistent Element Isolation
```css
::view-transition-group(persistent-nav) {
animation: none;
z-index: 100;
}
```
### Backdrop-Blur Workaround
For elements with `backdrop-filter`, hide the old snapshot to avoid flash:
```css
::view-transition-old(persistent-nav) {
display: none;
}
::view-transition-new(persistent-nav) {
animation: none;
}
```
---
## Reduced Motion
```css
@media (prefers-reduced-motion: reduce) {
::view-transition-old(*),
::view-transition-new(*),
::view-transition-group(*) {
animation-duration: 0s !important;
animation-delay: 0s !important;
}
}
```
# Implementation Workflow
Follow these steps in order when adding view transitions to an app. Each step builds on the previous one.
## Step 1: Audit the App
Before writing any code, scan the codebase thoroughly. Search for:
- **Every `<Link>` and `router.push`** — these are your navigation triggers. Open every file that contains one.
- **Every `<Suspense>` boundary** — each one is a candidate for a reveal animation. Check what its fallback renders.
- **Every page/route component** — list them all. Each page needs a VT placement decision.
- **Persistent elements** — headers, navbars, sidebars, sticky controls that stay on screen across navigations. These need `viewTransitionName` isolation.
- **Shared visual elements** — images, cards, or avatars that appear on both a source and target view (e.g., a thumbnail in a list and the same image on a detail page).
- **Skeleton-to-content control pairs** — if a Suspense fallback renders a control (search input, tab bar) that also exists in the real content, both need a matching `viewTransitionName`.
Then classify every navigation and produce a navigation map:
```
| Route | Navigates to | Direction | VT pattern |
|-----------------|----------------------|--------------|-----------------------|
| / | /detail/[id] | forward | directional slide |
| /detail/[id] | / | back | directional slide |
| /detail/[id] | /detail/[other] | sequential | directional slide (ordered prev/next) or key+share crossfade |
| /tab/[a] | /tab/[b] | lateral | key+share crossfade |
| (Suspense) | (content loads) | — | slide-up reveal |
```
For each shared element (`name` prop), note every navigation where a pair forms and where it doesn't — this determines whether you need `enter`/`exit` as a fallback alongside `share`.
## Step 2: Add CSS Recipes
Copy the **complete** CSS recipe set from `css-recipes.md` into your global stylesheet. This includes timing variables, shared keyframes, fade, slide (vertical), directional navigation (forward/back), shared element morph, persistent element isolation, and reduced motion.
Do not write your own animation CSS — the recipes handle staggered timing, motion blur on morphs, and reduced motion that are easy to get wrong. You can customize timing variables (`--duration-exit`, `--duration-enter`, `--duration-move`) after the initial setup.
## Step 3: Isolate Persistent Elements
For every persistent element identified in Step 1, add a `viewTransitionName` style to pull it out of the page content's transition snapshot:
```jsx
<header style={{ viewTransitionName: "site-header" }}>...</header>
```
Then add the persistent element isolation CSS from `css-recipes.md` (prevents the element from animating during page transitions). If the element uses `backdrop-blur` or `backdrop-filter`, use the backdrop-blur workaround from `css-recipes.md` instead.
If a Suspense fallback mirrors a persistent control (e.g., a skeleton search input), give both the real control and the skeleton the same `viewTransitionName` so they morph in place.
## Step 4: Add Directional Page Transitions
For hierarchical navigations identified in Step 1, tag the navigation direction using `addTransitionType` inside `startTransition`:
```jsx
startTransition(() => {
addTransitionType('nav-forward');
router.push('/detail/1');
});
```
Then wrap each **page component** (not layout) in a type-keyed `<ViewTransition>`:
```jsx
<ViewTransition
enter={{
"nav-forward": "nav-forward",
"nav-back": "nav-back",
default: "none",
}}
exit={{
"nav-forward": "nav-forward",
"nav-back": "nav-back",
default: "none",
}}
default="none"
>
<div>...page content...</div>
</ViewTransition>
```
The `nav-forward` and `nav-back` CSS classes from `css-recipes.md` produce horizontal slides. For simpler apps where directional motion isn't needed, a bare `<ViewTransition default="none">` wrapper with `enter="fade-in"` / `exit="fade-out"` works too.
Extract this into a reusable component so every page doesn't repeat the verbose type map:
```jsx
export function DirectionalTransition({ children }: { children: React.ReactNode }) {
return (
<ViewTransition
enter={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}
exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}
default="none"
>
{children}
</ViewTransition>
);
}
```
This also becomes the single place to adjust if you add new transition types later.
**Rules:**
- Always pair `enter` with `exit` — without an exit animation, the old page disappears instantly while the new one animates in.
- Always include `default: "none"` in type map objects and `default="none"` on the component — otherwise it fires on every transition.
- Place the directional `<ViewTransition>` in each page component, not in a layout. Layouts persist across navigations and never trigger enter/exit.
- Only use directional slides for hierarchical navigation or ordered sequences (prev/next). Lateral/sibling navigation (tab-to-tab) should use a bare `<ViewTransition>` (cross-fade) or `default="none"`.
## Step 5: Add Suspense Reveals
For every `<Suspense>` boundary identified in Step 1, wrap the fallback and content in separate `<ViewTransition>`s:
```jsx
<Suspense
fallback={
<ViewTransition exit="slide-down">
<Skeleton />
</ViewTransition>
}
>
<ViewTransition enter="slide-up" default="none">
<AsyncContent />
</ViewTransition>
</Suspense>
```
This example uses `slide-down` / `slide-up` for directional vertical motion. For a simpler reveal, a bare `<ViewTransition>` around the `<Suspense>` gives a cross-fade with zero configuration. Choose based on the spatial meaning — consult the "Choosing the Right Animation Style" table in the main skill file.
**Rules:**
- Always use `default="none"` on the content `<ViewTransition>` to prevent re-animation on revalidation or unrelated transitions.
- Use simple string props (not type maps) on Suspense `<ViewTransition>`s — Suspense resolves fire as separate transitions with no type, so type-keyed props won't match.
## Step 6: Add Shared Element Transitions
For every shared visual element identified in Step 1, add matching named `<ViewTransition>` wrappers on both the source and target views:
```jsx
// On the source view (e.g., list/grid page)
<ViewTransition name={`photo-${photo.id}`} share="morph" default="none">
<Image src={photo.src} ... />
</ViewTransition>
// On the target view (e.g., detail page) — same name
<ViewTransition name={`photo-${photo.id}`} share="morph">
<Image src={photo.src} ... />
</ViewTransition>
```
The `share="morph"` class uses the morph recipe from `css-recipes.md` (controlled duration + motion blur). For a simpler cross-fade, use `share="auto"` (browser default).
When list items contain shared elements, compose both patterns with two nested `<ViewTransition>` layers — see "Composing Shared Elements with List Identity" in `SKILL.md`.
**Rules:**
- Names must be globally unique — use prefixes like `photo-${id}`.
- Add `default="none"` on list-side shared elements to prevent per-item cross-fades on filter/search updates.
## Step 7: Verify Each Navigation Path
Walk through every row in the navigation map from Step 1 and confirm:
- Does the VT mount/unmount on this navigation, or does it stay mounted (same-route)?
- For named VTs: does a shared pair form? If not, does `enter`/`exit` provide a fallback?
- Does `default="none"` block an animation you actually want?
- Do persistent elements stay static (not sliding with page content)?
- Do Suspense reveals animate independently from directional navigations?
If any path produces no animation or competing animations, revisit the relevant step.
---
## Common Mistakes
- **Bare `<ViewTransition>` without props** — without `default="none"`, it fires the browser's default cross-fade on every transition (every navigation, every Suspense resolve, every revalidation). Always set `default="none"` and explicitly enable only the triggers you want.
- **Directional `<ViewTransition>` in a layout** — layouts persist across navigations and never unmount/remount. `enter`/`exit` props won't fire on route changes. Place the outer type-keyed `<ViewTransition>` in each page component.
- **Fade-out exit with shared element morphs** — the page dissolving conflicts with the morph. Use a directional slide exit instead.
- **Writing custom animation CSS** — the recipes in `css-recipes.md` handle staggered timing, motion blur on morphs, and reduced motion. Copy them; don't reinvent them.
- **Missing `default: "none"` in type-keyed objects** — TypeScript requires a `default` key, and without it the fallback is `"auto"` which fires on every transition.
- **Type maps on Suspense reveals** — Suspense resolves fire as separate transitions with no type. Type-keyed props won't match — use simple string props instead.
- **Raw `viewTransitionName` CSS to trigger animations** — React only calls `document.startViewTransition` when `<ViewTransition>` components are in the tree. A bare `viewTransitionName` style is for isolating elements from a parent's snapshot, not for triggering animations.
- **`update` trigger for same-route navigations** — nested VTs inside the content steal the mutation from the parent, so `update` never fires on the outer VT. Use `key` + `name` + `share` instead.
- **Named VT in a reusable component** — if a component with a named VT is rendered in both a modal/popover *and* a page, both mount simultaneously and break the morph. Make the name conditional or move it to the specific consumer.
- **`router.back()` for back navigation**`router.back()` triggers synchronous `popstate`, incompatible with view transitions. Use `router.push()` with an explicit URL.
---
For Next.js-specific implementation steps (config flag, `transitionTypes` on `<Link>`, same-route dynamic segments), see `nextjs.md`.
# View Transitions in Next.js
## Setup
`<ViewTransition>` works out of the box for `startTransition`/`Suspense` updates. To also animate `<Link>` navigations:
```js
// next.config.js
const nextConfig = {
experimental: { viewTransition: true },
};
module.exports = nextConfig;
```
This wraps every `<Link>` navigation in `document.startViewTransition`. Any VT with `default="auto"` fires on **every** link click — use `default="none"` to prevent competing animations.
Do **not** install `react@canary` — see SKILL.md "Availability" for details.
---
## Next.js Implementation Additions
When following `implementation.md`, apply these additions:
**After Step 2:** Enable the experimental flag above.
**Step 4:** Use `transitionTypes` on `<Link>` — see "The `transitionTypes` Prop" section below for usage and availability.
**After Step 6:** For same-route dynamic segments (e.g., `/collection/[slug]`), use the `key` + `name` + `share` pattern — see Same-Route Dynamic Segment Transitions below.
---
## Layout-Level ViewTransition
**Do NOT add a layout-level VT wrapping `{children}` if pages have their own VTs.** Nested VTs never fire enter/exit when inside a parent VT — page-level enter/exit will silently not work. Remove the layout VT entirely.
A bare `<ViewTransition>` in layout works only if pages have **no** VTs of their own.
**Layouts persist across navigations**`enter`/`exit` only fire on initial mount, not on route changes. Don't use type-keyed maps in layouts.
---
## The `transitionTypes` Prop on `next/link`
No wrapper component needed, works in Server Components:
```tsx
<Link href="/products/1" transitionTypes={['transition-to-detail']}>View Product</Link>
```
Replaces the manual pattern of `onNavigate` + `startTransition` + `addTransitionType` + `router.push()`. Reserve manual `startTransition` for non-link interactions (buttons, forms).
**Availability:** `transitionTypes` requires `experimental.viewTransition: true` and is available in Next.js 15+ canary builds and Next.js 16+. If unavailable, use `startTransition` + `addTransitionType` + `router.push()` (see Programmatic Navigation below). To check: `grep -r "transitionTypes" node_modules/next/dist/` — if no results, fall back to programmatic navigation.
---
## Programmatic Navigation
```tsx
'use client';
import { useRouter } from 'next/navigation';
import { startTransition, addTransitionType } from 'react';
function handleNavigate(href: string) {
const router = useRouter();
startTransition(() => {
addTransitionType('nav-forward');
router.push(href);
});
}
```
---
## Server-Side Filtering with `router.replace`
For search/sort/filter that re-renders on the server (via URL params), use `startTransition` + `router.replace`. VTs activate because the state update is inside `startTransition`:
```tsx
'use client';
import { useRouter } from 'next/navigation';
import { startTransition } from 'react';
function handleSort(sort: string) {
const router = useRouter();
startTransition(() => {
router.replace(`?sort=${sort}`);
});
}
```
List items wrapped in `<ViewTransition key={item.id}>` will animate reorder. This is the server-component alternative to the client-side `useDeferredValue` pattern in `patterns.md`.
---
## Two-Layer Pattern (Directional + Suspense)
Directional slides + Suspense reveals coexist because they fire at different moments. Place the directional VT in the **page component** (not layout):
```tsx
<ViewTransition
enter={{ "nav-forward": "slide-from-right", default: "none" }}
exit={{ "nav-forward": "slide-to-left", default: "none" }}
default="none"
>
<div>
<Suspense fallback={<ViewTransition exit="slide-down"><Skeleton /></ViewTransition>}>
<ViewTransition enter="slide-up" default="none"><Content /></ViewTransition>
</Suspense>
</div>
</ViewTransition>
```
---
## `loading.tsx` as Suspense Boundary
Next.js `loading.tsx` is an implicit `<Suspense>` boundary. Wrap the skeleton in `<ViewTransition exit="...">` in `loading.tsx`, and the content in `<ViewTransition enter="..." default="none">` in the page:
```tsx
// loading.tsx
<ViewTransition exit="slide-down"><PhotoGridSkeleton /></ViewTransition>
// page.tsx
<ViewTransition enter="slide-up" default="none"><PhotoGrid photos={photos} /></ViewTransition>
```
Same rules as explicit `<Suspense>`: use simple string props (not type maps) since Suspense reveals fire without transition types.
---
## Shared Elements Across Routes
```tsx
// List page
{products.map((product) => (
<Link key={product.id} href={`/products/${product.id}`} transitionTypes={['nav-forward']}>
<ViewTransition name={`product-${product.id}`}>
<Image src={product.image} alt={product.name} width={400} height={300} />
</ViewTransition>
</Link>
))}
// Detail page — same name
<ViewTransition name={`product-${product.id}`}>
<Image src={product.image} alt={product.name} width={800} height={600} />
</ViewTransition>
```
---
## Same-Route Dynamic Segment Transitions
When navigating between dynamic segments of the same route (e.g., `/collection/[slug]`), the page stays mounted — enter/exit never fire. Use `key` + `name` + `share`:
```tsx
<Suspense fallback={<Skeleton />}>
<ViewTransition key={slug} name={`collection-${slug}`} share="auto" default="none">
<Content slug={slug} />
</ViewTransition>
</Suspense>
```
- `key={slug}` forces unmount/remount on change
- `name` + `share="auto"` creates a shared element crossfade
- VT inside `<Suspense>` (without keying Suspense) keeps old content visible during loading
---
## Server Components
- `<ViewTransition>` works in both Server and Client Components
- `<Link transitionTypes>` works in Server Components — no `'use client'` needed
- `addTransitionType` and `startTransition` for programmatic nav require Client Components
# Patterns and Guidelines
## Searchable Grid with `useDeferredValue`
`useDeferredValue` makes filter updates a transition, activating `<ViewTransition>`:
```tsx
'use client';
import { useDeferredValue, useState, ViewTransition, Suspense } from 'react';
export default function SearchableGrid({ itemsPromise }) {
const [search, setSearch] = useState('');
const deferredSearch = useDeferredValue(search);
return (
<>
<input value={search} onChange={(e) => setSearch(e.currentTarget.value)} />
<ViewTransition>
<Suspense fallback={<GridSkeleton />}>
<ItemGrid itemsPromise={itemsPromise} search={deferredSearch} />
</Suspense>
</ViewTransition>
</>
);
}
```
Per-item `<ViewTransition name={...}>` inside a deferred list triggers cross-fades on every keystroke. Fix with `default="none"`:
```tsx
{filteredItems.map(item => (
<ViewTransition key={item.id} name={`item-${item.id}`} share="morph" default="none">
<ItemCard item={item} />
</ViewTransition>
))}
```
## Card Expand/Collapse with `startTransition`
Toggle between grid and detail view with shared element morph:
```tsx
'use client';
import { useState, useRef, startTransition, ViewTransition } from 'react';
export default function ItemGrid({ items }) {
const [expandedId, setExpandedId] = useState(null);
const scrollRef = useRef(0);
return expandedId ? (
<ViewTransition enter="slide-in" name={`item-${expandedId}`}>
<ItemDetail
item={items.find(i => i.id === expandedId)}
onClose={() => {
startTransition(() => {
setExpandedId(null);
setTimeout(() => window.scrollTo({ behavior: 'smooth', top: scrollRef.current }), 100);
});
}}
/>
</ViewTransition>
) : (
<div className="grid grid-cols-3 gap-4">
{items.map(item => (
<ViewTransition key={item.id} name={`item-${item.id}`}>
<ItemCard
item={item}
onSelect={() => {
scrollRef.current = window.scrollY;
startTransition(() => setExpandedId(item.id));
}}
/>
</ViewTransition>
))}
</div>
);
}
```
## Type-Safe Transition Helpers
Use `as const` arrays and derived types to prevent ID clashes:
```tsx
const transitionTypes = ['default', 'transition-to-detail', 'transition-to-list'] as const;
const animationTypes = ['auto', 'none', 'animate-slide-from-left', 'animate-slide-from-right'] as const;
type TransitionType = (typeof transitionTypes)[number];
type AnimationType = (typeof animationTypes)[number];
type TransitionMap = { default: AnimationType } & Partial<Record<Exclude<TransitionType, 'default'>, AnimationType>>;
export function HorizontalTransition({ children, enter, exit }: {
children: React.ReactNode;
enter: TransitionMap;
exit: TransitionMap;
}) {
return <ViewTransition enter={enter} exit={exit}>{children}</ViewTransition>;
}
```
## Cross-Fade Without Remount
Omit `key` to trigger an update (cross-fade) instead of exit + enter. Avoids Suspense remount/refetch:
```jsx
<ViewTransition>
<TabPanel tab={activeTab} />
</ViewTransition>
```
Use `key` when content identity changes (state resets). Omit for cross-fades (tabs, panels, carousel).
## Isolate Elements from Parent Animations
### Persistent Layout Elements
Persistent elements (headers, navbars, sidebars) get captured in the page's transition snapshot. Fix with `viewTransitionName`:
```jsx
<nav style={{ viewTransitionName: "persistent-nav" }}>{/* ... */}</nav>
```
Then add the persistent element isolation CSS from `css-recipes.md`. For `backdrop-blur`/`backdrop-filter`, use the backdrop-blur workaround from `css-recipes.md`.
### Floating Elements
Give popovers/tooltips their own `viewTransitionName`:
```jsx
<SelectPopover style={{ viewTransitionName: 'popover' }}>{options}</SelectPopover>
```
Global fix: see persistent element isolation in `css-recipes.md`.
## Shared Controls Between Skeleton and Content
Give matching controls in fallback and content the same `viewTransitionName`:
```jsx
// Fallback
<input disabled placeholder="Search..." style={{ viewTransitionName: 'search-input' }} />
// Content
<input placeholder="Search..." style={{ viewTransitionName: 'search-input' }} />
```
Don't put manual `viewTransitionName` on the root DOM node inside `<ViewTransition>` — React's auto-generated name overrides it.
## Reusable Animated Collapse
```jsx
function AnimatedCollapse({ open, children }) {
if (!open) return null;
return (
<ViewTransition enter="expand-in" exit="collapse-out">
{children}
</ViewTransition>
);
}
// Usage: toggle with startTransition
<button onClick={() => startTransition(() => setOpen(o => !o))}>Toggle</button>
<AnimatedCollapse open={open}><SectionContent /></AnimatedCollapse>
```
## Preserve State with Activity
```jsx
<Activity mode={isVisible ? 'visible' : 'hidden'}>
<ViewTransition enter="slide-in" exit="slide-out">
<Sidebar />
</ViewTransition>
</Activity>
```
## Exclude Elements with `useOptimistic`
`useOptimistic` values update before the transition snapshot, excluding them from animation. Use for controls (labels); use committed state for animated content:
```tsx
const [sort, setSort] = useState('newest');
const [optimisticSort, setOptimisticSort] = useOptimistic(sort);
function cycleSort() {
const nextSort = getNextSort(optimisticSort);
startTransition(() => {
setOptimisticSort(nextSort); // before snapshot — no animation
setSort(nextSort); // between snapshots — animates
});
}
<button>Sort: {LABELS[optimisticSort]}</button>
{items.sort(comparators[sort]).map(item => (
<ViewTransition key={item.id}><ItemCard item={item} /></ViewTransition>
))}
```
---
## View Transition Events
Imperative control via `onEnter`, `onExit`, `onUpdate`, `onShare`. Always return a cleanup function. `onShare` takes precedence over `onEnter`/`onExit`.
```jsx
<ViewTransition
onEnter={(instance, types) => {
const anim = instance.new.animate(
[{ transform: 'scale(0.8)', opacity: 0 }, { transform: 'scale(1)', opacity: 1 }],
{ duration: 300, easing: 'ease-out' }
);
return () => anim.cancel();
}}
>
<Component />
</ViewTransition>
```
The `instance` object: `instance.old`, `instance.new`, `instance.group`, `instance.imagePair`, `instance.name`.
The `types` array (second argument) lets you vary animation based on transition type.
---
## Animation Timing
| Interaction | Duration |
|------------|----------|
| Direct toggle (expand/collapse) | 100–200ms |
| Route transition (slide) | 150–250ms |
| Suspense reveal (skeleton → content) | 200–400ms |
| Shared element morph | 300–500ms |
---
## Troubleshooting
**VT not activating:** Ensure `<ViewTransition>` comes before any DOM node. Ensure state update is inside `startTransition`.
**"Two ViewTransition components with the same name":** Names must be globally unique. Use IDs: `name={`hero-${item.id}`}`.
**`router.back()` and browser back/forward skip animation:** Use `router.push()` with an explicit URL instead. See SKILL.md "router.back() and Browser Back Button."
**`flushSync` skips animations:** Use `startTransition` instead.
**Only updates animate (no enter/exit):** Without `<Suspense>`, React treats swaps as updates. Conditionally render the VT itself, or wrap in `<Suspense>`.
**Layout VT prevents page VTs from animating:** Nested VTs never fire enter/exit inside a parent VT. If your layout has a VT wrapping `{children}`, page-level enter/exit will silently not work. Remove the layout VT.
**List reorder not animating with `useOptimistic`:** Optimistic values resolve before snapshot. Use committed state for list order.
**TS error "Property 'default' is missing":** Type-keyed objects require a `default` key.
**Hash fragments cause scroll jumps:** Navigate without hash; scroll programmatically after navigation.
**Backdrop-blur flickers:** Use the backdrop-blur workaround from `css-recipes.md`.
**`border-radius` lost during transitions:** Apply `border-radius` directly to the captured element.
**Skeleton controls slide away:** Give matching controls the same `viewTransitionName`.
**Batching:** Multiple updates during animation are batched. A→B→C→D becomes B→D.
---
name: web-design-guidelines
description: Review UI code for Web Interface Guidelines compliance. Use when asked to "review my UI", "check accessibility", "audit design", "review UX", or "check my site against best practices".
metadata:
author: vercel
version: "1.0.0"
argument-hint: <file-or-pattern>
---
# Web Interface Guidelines
Review files for compliance with Web Interface Guidelines.
## How It Works
1. Fetch the latest guidelines from the source URL below
2. Read the specified files (or prompt user for files/pattern)
3. Check against all rules in the fetched guidelines
4. Output findings in the terse `file:line` format
## Guidelines Source
Fetch fresh guidelines before each review:
```
https://raw.githubusercontent.com/vercel-labs/web-interface-guidelines/main/command.md
```
Use WebFetch to retrieve the latest rules. The fetched content contains all the rules and output format instructions.
## Usage
When a user provides a file or pattern argument:
1. Fetch guidelines from the source URL above
2. Read the specified files
3. Apply all rules from the fetched guidelines
4. Output findings using the format specified in the guidelines
If no files specified, ask the user which files to review.
{
"version": 1,
"skills": {
"vercel-composition-patterns": {
"source": "vercel-labs/agent-skills",
"sourceType": "github",
"skillPath": "skills/composition-patterns/SKILL.md",
"computedHash": "575757e3e25761c8c562d6e395d29f0b76c98b1273c0bd72d88e6ab1bc9c7d42"
},
"vercel-react-best-practices": {
"source": "vercel-labs/agent-skills",
"sourceType": "github",
"skillPath": "skills/react-best-practices/SKILL.md",
"computedHash": "ca7b0c0c6e5f2750043f7f0cd72d16ac4e2abc48f9b5500d047a4b77a2506212"
},
"vercel-react-view-transitions": {
"source": "vercel-labs/agent-skills",
"sourceType": "github",
"skillPath": "skills/react-view-transitions/SKILL.md",
"computedHash": "c8952fc9127fa0564d0cb71dccb4215a5608ac933b5831104f09173a97a46f85"
},
"web-design-guidelines": {
"source": "vercel-labs/agent-skills",
"sourceType": "github",
"skillPath": "skills/web-design-guidelines/SKILL.md",
"computedHash": "f3bc47f890f42a44db1007ab390709ec368e4b8c089baee6b0007182236ac474"
}
}
}
'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
export default function CategoriesPage() {
const router = useRouter();
useEffect(() => {
router.replace('/admin/header-config');
}, [router]);
return null;
}
'use client';
import React from 'react';
import Link from 'next/link';
import { useGetNewsAdmin } from '@/api/endpoints/news';
import { useGetOrganizations } from '@/api/endpoints/organizations';
import { useGetContact } from '@/api/endpoints/contact';
import { useGetNewsPageConfigGetHierarchical } from '@/api/endpoints/news-page-config';
import { GetNewsResponseType } from '@/api/types/news';
import { GetNewsPageConfigResponseType } from '@/api/types/news-page-config';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import {
ArrowRight,
BarChart3,
Building2,
FileText,
Layers,
Mail,
Newspaper,
Users,
} from 'lucide-react';
function extractCount(
value: unknown,
): number | undefined {
if (!value || typeof value !== 'object') return undefined;
const source = value as {
responseData?: { count?: number };
data?: { count?: number; responseData?: { count?: number } };
};
return (
source.responseData?.count ??
source.data?.responseData?.count ??
source.data?.count
);
}
interface StatCardProps {
title: string;
value: number | string | undefined;
icon: React.ReactNode;
href: string;
color: string;
isLoading?: boolean;
}
function StatCard({ title, value, icon, href, color, isLoading }: StatCardProps) {
return (
<Link href={href}>
<Card className="cursor-pointer transition-shadow hover:shadow-md">
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div className="flex-1">
<p className="text-sm font-medium text-gray-500">{title}</p>
{isLoading ? (
<Skeleton className="mt-2 h-8 w-20" />
) : (
<p className="mt-1 text-3xl font-bold text-gray-900">{value ?? '—'}</p>
)}
</div>
<div
className={`flex h-14 w-14 items-center justify-center rounded-2xl text-white shadow-sm ${color}`}
>
{icon}
</div>
</div>
<div className="mt-4 flex items-center gap-1 text-xs text-[#063e8e] opacity-0 transition-opacity group-hover:opacity-100">
<span>Xem chi tiết</span>
<ArrowRight className="h-3 w-3" />
</div>
</CardContent>
</Card>
</Link>
);
}
export default function DashboardPage() {
const { data: newsData, isLoading: newsLoading } =
useGetNewsAdmin<GetNewsResponseType>({ pageSize: '1' });
const { data: configData, isLoading: configLoading } =
useGetNewsPageConfigGetHierarchical<GetNewsPageConfigResponseType>();
const { data: orgData, isLoading: orgLoading } = useGetOrganizations({ pageSize: '1' });
const { data: contactData, isLoading: contactLoading } = useGetContact();
const stats = [
{
title: 'Tổng bài viết',
value: newsData?.responseData?.count,
icon: <Newspaper className="h-7 w-7" />,
href: '/admin/news',
color: 'bg-[#063e8e]',
isLoading: newsLoading,
},
{
title: 'Cấu hình Danh mục',
value: configData?.responseData ? 'Đã cấu hình' : '—',
icon: <Layers className="h-7 w-7" />,
href: '/admin/header-config',
color: 'bg-violet-500',
isLoading: configLoading,
},
{
title: 'Hội viên',
value: extractCount(orgData),
icon: <Users className="h-7 w-7" />,
href: '/admin/members',
color: 'bg-orange-500',
isLoading: orgLoading,
},
{
title: 'Liên hệ / Email',
value: extractCount(contactData),
icon: <Mail className="h-7 w-7" />,
href: '/admin/emails',
color: 'bg-pink-500',
isLoading: contactLoading,
},
];
const quickLinks = [
{ label: 'Thêm bài viết mới', href: '/admin/news/new', icon: <FileText className="h-4 w-4" /> },
{ label: 'Cấu hình menu Header', href: '/admin/header-config', icon: <Layers className="h-4 w-4" /> },
{ label: 'Quản lý Hội viên', href: '/admin/members', icon: <Users className="h-4 w-4" /> },
{ label: 'Đối tác', href: '/admin/partners', icon: <Building2 className="h-4 w-4" /> },
{ label: 'Thông tin website', href: '/admin/website-config', icon: <BarChart3 className="h-4 w-4" /> },
];
return (
<div className="space-y-8">
<div className="flex items-center justify-between">
<div>
<h2 className="text-3xl font-bold tracking-tight text-gray-900">Tổng quan hệ thống</h2>
<p className="mt-1 text-sm font-medium text-gray-600">
Chào mừng trở lại! Đây là tóm tắt hoạt động của VCCI News.
</p>
</div>
<Badge variant="outline" className="border-[#063e8e]/30 text-[#063e8e]">
Cập nhật: {new Date().toLocaleDateString('vi-VN')}
</Badge>
</div>
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2 xl:grid-cols-4">
{stats.map((item) => (
<StatCard key={item.href} {...item} />
))}
</div>
<Card>
<CardHeader>
<CardTitle className="text-base font-semibold text-gray-800">Truy cập nhanh</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
{quickLinks.map((item) => (
<Link
key={item.href}
href={item.href}
className="flex flex-col items-center gap-2 rounded-xl border border-[#063e8e]/15 p-4 text-center text-sm text-gray-700 transition-all hover:border-[#063e8e]/40 hover:bg-[#063e8e]/5 hover:text-[#063e8e]"
>
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-[#063e8e]/10 text-[#063e8e]">
{item.icon}
</div>
<span className="text-xs font-medium leading-tight">{item.label}</span>
</Link>
))}
</div>
</CardContent>
</Card>
</div>
);
}
'use client';
import React, { useState } from 'react';
import { useGetContact } from '@/api/endpoints/contact';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Search, Mail } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import dayjs from 'dayjs';
export default function EmailsPage() {
const [search, setSearch] = useState('');
const [page, setPage] = useState(1);
const pageSize = 20;
const { data, isLoading } = useGetContact({} as any);
const allRows = (data as any)?.responseData?.rows ?? (data as any)?.data?.rows ?? [];
const filtered = search
? allRows.filter(
(r: any) =>
r.email?.includes(search) ||
r.full_name?.toLowerCase().includes(search.toLowerCase()) ||
r.organization_name?.toLowerCase().includes(search.toLowerCase()),
)
: allRows;
const total = filtered.length;
const totalPages = Math.ceil(total / pageSize);
const rows = filtered.slice((page - 1) * pageSize, page * pageSize);
return (
<div>
<div className="flex items-center justify-between mb-6">
<div>
<h2 className="text-xl font-bold text-gray-800">Quản lý Email nhận thông tin</h2>
<p className="text-sm text-gray-500 mt-1">
Danh sách các địa chỉ email / liên hệ nhận thông tin từ VCCI.
</p>
</div>
<Badge variant="outline" className="border-pink-300 text-pink-600 text-sm px-3 py-1">
<Mail className="h-3.5 w-3.5 mr-1" />
{total} email
</Badge>
</div>
<div className="relative w-72 mb-4">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
<Input
className="pl-9"
placeholder="Tìm email, tên, tổ chức..."
value={search}
onChange={(e) => { setSearch(e.target.value); setPage(1); }}
/>
</div>
<div className="bg-white rounded-lg border shadow-sm overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-8">#</TableHead>
<TableHead>Email</TableHead>
<TableHead>Họ tên</TableHead>
<TableHead>Tổ chức</TableHead>
<TableHead>Số điện thoại</TableHead>
<TableHead>Nhu cầu</TableHead>
<TableHead>Ngày gửi</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoading ? (
Array.from({ length: 5 }).map((_, i) => (
<TableRow key={i}>
{Array.from({ length: 7 }).map((_, j) => (
<TableCell key={j}><Skeleton className="h-4 w-full" /></TableCell>
))}
</TableRow>
))
) : rows.length === 0 ? (
<TableRow>
<TableCell colSpan={7} className="text-center text-gray-400 py-10 text-sm">
Chưa có thông tin email nào.
</TableCell>
</TableRow>
) : rows.map((item: any, idx: number) => (
<TableRow key={item.id ?? idx}>
<TableCell className="text-gray-400 text-sm">{(page - 1) * pageSize + idx + 1}</TableCell>
<TableCell>
<a href={`mailto:${item.email}`} className="text-sm font-medium text-blue-600 hover:underline">
{item.email}
</a>
</TableCell>
<TableCell className="text-sm">{item.full_name || '—'}</TableCell>
<TableCell className="text-sm text-gray-600 max-w-40 truncate">
{item.organization_name || '—'}
</TableCell>
<TableCell className="text-sm text-gray-600">{item.phone || '—'}</TableCell>
<TableCell className="text-sm text-gray-500 max-w-[140px] truncate">
{item.demand || '—'}
</TableCell>
<TableCell className="text-gray-400 text-sm">
{item.created_at ? dayjs(item.created_at).format('DD/MM/YYYY') : '—'}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
{totalPages > 1 && (
<div className="flex justify-end gap-2 mt-4">
<Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>Trước</Button>
<span className="text-sm text-gray-500 self-center">{page} / {totalPages}</span>
<Button variant="outline" size="sm" disabled={page >= totalPages} onClick={() => setPage((p) => p + 1)}>Sau</Button>
</div>
)}
</div>
);
}
'use client';
import React from 'react';
import Link from 'next/link';
import { useParams, useRouter } from 'next/navigation';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import {
buildHeaderCategoryTree,
getHeaderCategorySeed,
HEADER_CONFIG_STORAGE_KEY,
HeaderCategoryItem,
normalizeHeaderCategories,
} from '@/mockdata/header-config';
import {
createHeaderCategoryPostId,
EMPTY_HEADER_CATEGORY_POST_FORM,
getHeaderCategoryPostSeed,
HEADER_CATEGORY_POSTS_STORAGE_KEY,
HeaderCategoryPostFormValues,
HeaderCategoryPostItem,
makeHeaderCategoryPostSlug,
normalizeHeaderCategoryPosts,
} from '@/mockdata/header-category-posts';
import { ArrowLeft, Save } from 'lucide-react';
const fieldClassName =
'border-[#063e8e]/15 bg-white text-gray-700 placeholder:text-gray-700 focus-visible:ring-[#063e8e]/30';
function getInitialHeaderConfig() {
if (typeof window === 'undefined') {
return getHeaderCategorySeed();
}
const raw = window.localStorage.getItem(HEADER_CONFIG_STORAGE_KEY);
if (!raw) return getHeaderCategorySeed();
try {
const parsed = JSON.parse(raw) as HeaderCategoryItem[];
if (!Array.isArray(parsed) || parsed.length === 0) {
return getHeaderCategorySeed();
}
return normalizeHeaderCategories(parsed);
} catch {
return getHeaderCategorySeed();
}
}
function useHeaderConfigModule() {
const [items, setItems] = React.useState<HeaderCategoryItem[]>([]);
const [isReady, setIsReady] = React.useState(false);
React.useEffect(() => {
setItems(getInitialHeaderConfig());
setIsReady(true);
}, []);
const tree = React.useMemo(() => buildHeaderCategoryTree(items), [items]);
return {
tree,
isReady,
};
}
function getInitialHeaderCategoryPosts() {
if (typeof window === 'undefined') {
return getHeaderCategoryPostSeed();
}
const raw = window.localStorage.getItem(HEADER_CATEGORY_POSTS_STORAGE_KEY);
if (!raw) return getHeaderCategoryPostSeed();
try {
const parsed = JSON.parse(raw) as HeaderCategoryPostItem[];
if (!Array.isArray(parsed) || parsed.length === 0) {
return getHeaderCategoryPostSeed();
}
return normalizeHeaderCategoryPosts(parsed);
} catch {
return getHeaderCategoryPostSeed();
}
}
function persistHeaderCategoryPosts(items: HeaderCategoryPostItem[]) {
if (typeof window === 'undefined') return;
window.localStorage.setItem(
HEADER_CATEGORY_POSTS_STORAGE_KEY,
JSON.stringify(normalizeHeaderCategoryPosts(items)),
);
}
function upsertPost(items: HeaderCategoryPostItem[], post: HeaderCategoryPostItem) {
const exists = items.some((item) => item.id === post.id);
return normalizeHeaderCategoryPosts(
exists ? items.map((item) => (item.id === post.id ? post : item)) : [...items, post],
);
}
function useHeaderCategoryPostsModule() {
const [items, setItems] = React.useState<HeaderCategoryPostItem[]>([]);
const [isReady, setIsReady] = React.useState(false);
React.useEffect(() => {
setItems(getInitialHeaderCategoryPosts());
setIsReady(true);
}, []);
React.useEffect(() => {
if (!isReady) return;
persistHeaderCategoryPosts(items);
}, [isReady, items]);
const getPostsByCategory = React.useCallback(
(categoryId: string) => items.filter((item) => item.category_id === categoryId),
[items],
);
const getPostById = React.useCallback(
(postId: string) => items.find((item) => item.id === postId) ?? null,
[items],
);
const createPost = React.useCallback(
(categoryId: string, values: HeaderCategoryPostFormValues) => {
const now = new Date().toISOString();
const nextPost: HeaderCategoryPostItem = {
id: createHeaderCategoryPostId(),
category_id: categoryId,
title: values.title.trim(),
slug: values.slug.trim() || makeHeaderCategoryPostSlug(values.title),
excerpt: values.excerpt.trim(),
content: values.content.trim(),
thumbnail: values.thumbnail.trim(),
published_at: values.published_at || now.slice(0, 10),
is_active: values.is_active,
created_at: now,
updated_at: now,
};
setItems((current) => upsertPost(current, nextPost));
return nextPost;
},
[],
);
const updatePost = React.useCallback((postId: string, values: HeaderCategoryPostFormValues) => {
let updatedPost: HeaderCategoryPostItem | null = null;
setItems((current) => {
const existing = current.find((item) => item.id === postId);
if (!existing) return current;
updatedPost = {
...existing,
title: values.title.trim(),
slug: values.slug.trim() || makeHeaderCategoryPostSlug(values.title),
excerpt: values.excerpt.trim(),
content: values.content.trim(),
thumbnail: values.thumbnail.trim(),
published_at: values.published_at || existing.published_at,
is_active: values.is_active,
updated_at: new Date().toISOString(),
};
return upsertPost(current, updatedPost);
});
return updatedPost;
}, []);
const toFormValues = React.useCallback(
(post?: HeaderCategoryPostItem | null): HeaderCategoryPostFormValues => {
if (!post) return EMPTY_HEADER_CATEGORY_POST_FORM;
return {
id: post.id,
title: post.title,
slug: post.slug,
excerpt: post.excerpt,
content: post.content,
thumbnail: post.thumbnail,
published_at: post.published_at,
is_active: post.is_active,
};
},
[],
);
return {
isReady,
getPostsByCategory,
getPostById,
createPost,
updatePost,
toFormValues,
};
}
export default function HeaderCategoryPostFormPage() {
const params = useParams();
const router = useRouter();
const categoryId = String(params.categoryId ?? '');
const postId = String(params.postId ?? '');
const isCreate = postId === 'new';
const { tree, isReady: categoriesReady } = useHeaderConfigModule();
const {
isReady: postsReady,
getPostsByCategory,
getPostById,
createPost,
updatePost,
toFormValues,
} = useHeaderCategoryPostsModule();
const [form, setForm] = React.useState<HeaderCategoryPostFormValues>(
EMPTY_HEADER_CATEGORY_POST_FORM,
);
const flatCategories = React.useMemo(() => {
const rows: typeof tree = [];
const walk = (items: typeof tree) => {
items.forEach((item) => {
rows.push(item);
if (item.children.length > 0) {
walk(item.children);
}
});
};
walk(tree);
return rows;
}, [tree]);
const category = React.useMemo(
() => flatCategories.find((item) => item.id === categoryId) ?? null,
[categoryId, flatCategories],
);
const post = React.useMemo(() => {
if (isCreate) return null;
return getPostById(postId);
}, [getPostById, isCreate, postId]);
const categoryPosts = React.useMemo(
() => getPostsByCategory(categoryId),
[categoryId, getPostsByCategory],
);
const isSinglePostCategory = category?.type === 'page';
const canManagePosts = Boolean(
category && (category.type === 'page' || category.type === 'news' || category.type === 'image'),
);
React.useEffect(() => {
if (!postsReady) return;
if (isCreate) {
setForm(EMPTY_HEADER_CATEGORY_POST_FORM);
return;
}
setForm(toFormValues(post));
}, [isCreate, post, postsReady, toFormValues]);
React.useEffect(() => {
if (!categoriesReady || !postsReady) return;
if (!category || !canManagePosts) {
router.replace('/admin/header-config');
return;
}
if (isCreate && isSinglePostCategory && categoryPosts.length >= 1) {
toast.error('Danh mục bài viết trang chỉ được tạo 1 bài viết');
router.replace(`/admin/header-config/${categoryId}/posts`);
return;
}
if (!isCreate && !post) {
router.replace(`/admin/header-config/${categoryId}/posts`);
}
}, [
canManagePosts,
categoriesReady,
category,
categoryId,
categoryPosts.length,
isCreate,
isSinglePostCategory,
post,
postsReady,
router,
]);
const setField = <K extends keyof HeaderCategoryPostFormValues>(
key: K,
value: HeaderCategoryPostFormValues[K],
) => {
setForm((previous) => ({ ...previous, [key]: value }));
};
const handleTitleChange = (value: string) => {
setForm((previous) => ({
...previous,
title: value,
slug:
value
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/đ/g, 'd')
.replace(/Đ/g, 'D')
.toLowerCase()
.trim()
.replace(/[^a-z0-9\\s-]/g, '')
.replace(/\\s+/g, '-')
.replace(/-+/g, '-') || previous.slug,
}));
};
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!form.title.trim()) {
toast.error('Tiêu đề bài viết là bắt buộc');
return;
}
if (isCreate) {
createPost(categoryId, form);
toast.success('Đã tạo bài viết');
} else {
updatePost(postId, form);
toast.success('Đã cập nhật bài viết');
}
router.push(`/admin/header-config/${categoryId}/posts`);
};
if (!categoriesReady || !postsReady || !category || !canManagePosts || (!isCreate && !post)) {
return (
<div className="rounded-2xl border border-[#063e8e]/15 bg-white p-8 text-center text-sm text-gray-700 shadow-sm">
Đang tải form bài viết...
</div>
);
}
return (
<div className="mx-auto max-w-5xl space-y-6">
<div className="flex flex-col gap-4 rounded-2xl border border-[#063e8e]/15 bg-white p-6 shadow-sm">
<Button
variant="ghost"
asChild
className="h-9 w-fit px-3 text-gray-700 hover:bg-[#063e8e]/10 hover:text-[#063e8e]"
>
<Link href={`/admin/header-config/${categoryId}/posts`}>
<ArrowLeft className="mr-2 h-4 w-4" />
Quay lại danh sách bài viết
</Link>
</Button>
<div className="space-y-2">
<h2 className="text-2xl font-semibold text-[#063e8e]">
{isCreate ? 'Thêm bài viết mới' : 'Chỉnh sửa bài viết'}
</h2>
<p className="text-sm text-gray-700">
Danh mục hiện tại: <span className="font-medium text-black">{category.name}</span>
</p>
</div>
</div>
<form
onSubmit={handleSubmit}
className="space-y-6 rounded-2xl border border-[#063e8e]/15 bg-white p-6 shadow-sm"
>
<div className="grid grid-cols-1 gap-5 md:grid-cols-2">
<div className="md:col-span-2">
<Label className="mb-1.5 block text-gray-700">Tiêu đề bài viết *</Label>
<Input
required
value={form.title}
onChange={(event) => handleTitleChange(event.target.value)}
placeholder="Nhập tiêu đề bài viết"
className={fieldClassName}
/>
</div>
<div>
<Label className="mb-1.5 block text-gray-700">Slug</Label>
<Input
value={form.slug}
onChange={(event) => setField('slug', event.target.value)}
placeholder="tieu-de-bai-viet"
className={fieldClassName}
/>
</div>
<div>
<Label className="mb-1.5 block text-gray-700">Ngày đăng</Label>
<Input
type="date"
value={form.published_at}
onChange={(event) => setField('published_at', event.target.value)}
className={fieldClassName}
/>
</div>
<div className="md:col-span-2">
<Label className="mb-1.5 block text-gray-700">Ảnh đại diện</Label>
<Input
value={form.thumbnail}
onChange={(event) => setField('thumbnail', event.target.value)}
placeholder="https://..."
className={fieldClassName}
/>
{form.thumbnail ? (
<div className="mt-3 overflow-hidden rounded-xl border border-[#063e8e]/15 bg-[#063e8e]/5 p-2">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={form.thumbnail}
alt={form.title || 'thumbnail'}
className="h-48 w-full rounded-lg object-cover"
/>
</div>
) : null}
</div>
<div className="md:col-span-2">
<Label className="mb-1.5 block text-gray-700">Tóm tắt</Label>
<Textarea
rows={4}
value={form.excerpt}
onChange={(event) => setField('excerpt', event.target.value)}
placeholder="Nhập mô tả ngắn cho bài viết"
className={fieldClassName}
/>
</div>
<div className="md:col-span-2">
<Label className="mb-1.5 block text-gray-700">Nội dung</Label>
<Textarea
rows={12}
value={form.content}
onChange={(event) => setField('content', event.target.value)}
placeholder="<p>Nội dung bài viết...</p>"
className={`${fieldClassName} font-mono text-sm`}
/>
</div>
</div>
<div className="flex items-center gap-3 rounded-xl border border-[#063e8e]/15 bg-[#063e8e]/5 px-4 py-3">
<Switch
checked={form.is_active}
onCheckedChange={(checked) => setField('is_active', checked)}
className="data-[state=checked]:bg-[#063e8e] data-[state=unchecked]:bg-gray-300"
/>
<Label className="cursor-pointer text-sm text-gray-700">Hiển thị bài viết</Label>
</div>
<div className="flex justify-end gap-3 pt-2">
<Button
type="button"
variant="outline"
asChild
className="border-[#063e8e]/15 bg-white text-gray-700 hover:bg-[#063e8e]/10 hover:text-[#063e8e]"
>
<Link href={`/admin/header-config/${categoryId}/posts`}>Hủy</Link>
</Button>
<Button type="submit" className="bg-[#063e8e] text-white hover:bg-[#063e8e]/90">
<Save className="mr-2 h-4 w-4" />
{isCreate ? 'Lưu bài viết' : 'Cập nhật bài viết'}
</Button>
</div>
</form>
</div>
);
}
'use client';
import React from 'react';
import Link from 'next/link';
import { useParams, useRouter } from 'next/navigation';
import { toast } from 'sonner';
import dayjs from 'dayjs';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import {
buildHeaderCategoryTree,
getHeaderCategorySeed,
HEADER_CONFIG_STORAGE_KEY,
HeaderCategoryItem,
HeaderCategoryType,
normalizeHeaderCategories,
} from '@/mockdata/header-config';
import {
createHeaderCategoryPostId,
getHeaderCategoryPostSeed,
HEADER_CATEGORY_POSTS_STORAGE_KEY,
HeaderCategoryPostFormValues,
HeaderCategoryPostItem,
makeHeaderCategoryPostSlug,
normalizeHeaderCategoryPosts,
} from '@/mockdata/header-category-posts';
import {
ArrowLeft,
Eye,
EyeOff,
Image as ImageIcon,
Pencil,
Plus,
Search,
Trash2,
} from 'lucide-react';
function getInitialHeaderConfig() {
if (typeof window === 'undefined') {
return getHeaderCategorySeed();
}
const raw = window.localStorage.getItem(HEADER_CONFIG_STORAGE_KEY);
if (!raw) return getHeaderCategorySeed();
try {
const parsed = JSON.parse(raw) as HeaderCategoryItem[];
if (!Array.isArray(parsed) || parsed.length === 0) {
return getHeaderCategorySeed();
}
return normalizeHeaderCategories(parsed);
} catch {
return getHeaderCategorySeed();
}
}
function useHeaderConfigModule() {
const [items, setItems] = React.useState<HeaderCategoryItem[]>([]);
const [isReady, setIsReady] = React.useState(false);
React.useEffect(() => {
setItems(getInitialHeaderConfig());
setIsReady(true);
}, []);
const tree = React.useMemo(() => buildHeaderCategoryTree(items), [items]);
return {
tree,
isReady,
};
}
function getInitialHeaderCategoryPosts() {
if (typeof window === 'undefined') {
return getHeaderCategoryPostSeed();
}
const raw = window.localStorage.getItem(HEADER_CATEGORY_POSTS_STORAGE_KEY);
if (!raw) return getHeaderCategoryPostSeed();
try {
const parsed = JSON.parse(raw) as HeaderCategoryPostItem[];
if (!Array.isArray(parsed) || parsed.length === 0) {
return getHeaderCategoryPostSeed();
}
return normalizeHeaderCategoryPosts(parsed);
} catch {
return getHeaderCategoryPostSeed();
}
}
function persistHeaderCategoryPosts(items: HeaderCategoryPostItem[]) {
if (typeof window === 'undefined') return;
window.localStorage.setItem(
HEADER_CATEGORY_POSTS_STORAGE_KEY,
JSON.stringify(normalizeHeaderCategoryPosts(items)),
);
}
function upsertPost(items: HeaderCategoryPostItem[], post: HeaderCategoryPostItem) {
const exists = items.some((item) => item.id === post.id);
return normalizeHeaderCategoryPosts(
exists ? items.map((item) => (item.id === post.id ? post : item)) : [...items, post],
);
}
function useHeaderCategoryPostsModule() {
const [items, setItems] = React.useState<HeaderCategoryPostItem[]>([]);
const [isReady, setIsReady] = React.useState(false);
React.useEffect(() => {
setItems(getInitialHeaderCategoryPosts());
setIsReady(true);
}, []);
React.useEffect(() => {
if (!isReady) return;
persistHeaderCategoryPosts(items);
}, [isReady, items]);
const getPostsByCategory = React.useCallback(
(categoryId: string) => items.filter((item) => item.category_id === categoryId),
[items],
);
const getPostById = React.useCallback(
(postId: string) => items.find((item) => item.id === postId) ?? null,
[items],
);
const createPost = React.useCallback(
(categoryId: string, values: HeaderCategoryPostFormValues) => {
const now = new Date().toISOString();
const nextPost: HeaderCategoryPostItem = {
id: createHeaderCategoryPostId(),
category_id: categoryId,
title: values.title.trim(),
slug: values.slug.trim() || makeHeaderCategoryPostSlug(values.title),
excerpt: values.excerpt.trim(),
content: values.content.trim(),
thumbnail: values.thumbnail.trim(),
published_at: values.published_at || now.slice(0, 10),
is_active: values.is_active,
created_at: now,
updated_at: now,
};
setItems((current) => upsertPost(current, nextPost));
return nextPost;
},
[],
);
const updatePost = React.useCallback((postId: string, values: HeaderCategoryPostFormValues) => {
let updatedPost: HeaderCategoryPostItem | null = null;
setItems((current) => {
const existing = current.find((item) => item.id === postId);
if (!existing) return current;
updatedPost = {
...existing,
title: values.title.trim(),
slug: values.slug.trim() || makeHeaderCategoryPostSlug(values.title),
excerpt: values.excerpt.trim(),
content: values.content.trim(),
thumbnail: values.thumbnail.trim(),
published_at: values.published_at || existing.published_at,
is_active: values.is_active,
updated_at: new Date().toISOString(),
};
return upsertPost(current, updatedPost);
});
return updatedPost;
}, []);
const removePost = React.useCallback((postId: string) => {
setItems((current) => current.filter((item) => item.id !== postId));
}, []);
return {
isReady,
getPostsByCategory,
getPostById,
createPost,
updatePost,
removePost,
};
}
function getTypeLabel(type: HeaderCategoryType) {
switch (type) {
case 'page':
return 'Bài viết trang';
case 'news':
return 'Tin tức';
case 'image':
return 'Ảnh';
case 'category':
return 'Danh mục';
default:
return type;
}
}
export default function HeaderCategoryPostsPage() {
const params = useParams();
const router = useRouter();
const categoryId = String(params.categoryId ?? '');
const { tree, isReady: categoryReady } = useHeaderConfigModule();
const { isReady: postsReady, getPostsByCategory, removePost } = useHeaderCategoryPostsModule();
const [search, setSearch] = React.useState('');
const [deleteId, setDeleteId] = React.useState<string | null>(null);
const flatCategories = React.useMemo(() => {
const rows: typeof tree = [];
const walk = (items: typeof tree) => {
items.forEach((item) => {
rows.push(item);
if (item.children.length > 0) {
walk(item.children);
}
});
};
walk(tree);
return rows;
}, [tree]);
const category = React.useMemo(
() => flatCategories.find((item) => item.id === categoryId) ?? null,
[categoryId, flatCategories],
);
const posts = React.useMemo(() => getPostsByCategory(categoryId), [categoryId, getPostsByCategory]);
const filteredPosts = React.useMemo(() => {
const keyword = search.trim().toLowerCase();
if (!keyword) return posts;
return posts.filter(
(post) =>
post.title.toLowerCase().includes(keyword) ||
post.slug.toLowerCase().includes(keyword) ||
post.excerpt.toLowerCase().includes(keyword),
);
}, [posts, search]);
const isSinglePostCategory = category?.type === 'page';
const canCreatePost = Boolean(
category && (category.type === 'page' || category.type === 'news' || category.type === 'image'),
);
const createLabel = category?.type === 'image' ? 'Thêm ảnh' : 'Thêm bài viết';
React.useEffect(() => {
if (!categoryReady || !postsReady) return;
if (!category || !canCreatePost) {
router.replace('/admin/header-config');
}
}, [canCreatePost, category, categoryReady, postsReady, router]);
if (!categoryReady || !postsReady || !category || !canCreatePost) {
return (
<div className="rounded-2xl border border-[#063e8e]/15 bg-white p-8 text-center text-sm text-gray-700 shadow-sm">
Đang tải dữ liệu danh mục...
</div>
);
}
return (
<div className="space-y-6">
<div className="flex flex-col gap-4 rounded-2xl border border-[#063e8e]/15 bg-white p-6 shadow-sm lg:flex-row lg:items-start lg:justify-between">
<div className="space-y-3">
<Button
variant="ghost"
asChild
className="h-9 w-fit px-3 text-gray-700 hover:bg-[#063e8e]/10 hover:text-[#063e8e]"
>
<Link href="/admin/header-config">
<ArrowLeft className="mr-2 h-4 w-4" />
Quay lại cấu hình danh mục
</Link>
</Button>
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-3">
<h2 className="text-2xl font-semibold text-[#063e8e]">{category.name}</h2>
<Badge variant="outline" className="border-[#063e8e]/20 text-[#063e8e]">
{getTypeLabel(category.type)}
</Badge>
</div>
<p className="max-w-3xl text-sm text-gray-700">
{isSinglePostCategory
? 'Danh mục dạng bài viết trang chỉ cho phép gắn đúng 1 bài viết. Nếu cần thay nội dung, hãy chỉnh sửa bài hiện có hoặc xóa rồi tạo lại.'
: category.type === 'image'
? 'Danh mục dạng ảnh cho phép thêm nhiều nội dung và quản lý tập trung theo đúng cấu trúc header.'
: 'Danh mục dạng tin tức cho phép thêm nhiều bài viết và quản lý tập trung theo đúng cấu trúc header.'}
</p>
</div>
</div>
<div className="flex flex-wrap items-center gap-3">
<div className="rounded-xl border border-[#063e8e]/15 bg-[#063e8e]/5 px-4 py-3 text-sm text-gray-700">
<span className="font-semibold text-[#063e8e]">{posts.length}</span> bài viết
</div>
{canCreatePost && (!isSinglePostCategory || posts.length < 1) ? (
<Button asChild className="bg-[#063e8e] text-white hover:bg-[#063e8e]/90">
<Link href={`/admin/header-config/${category.id}/posts/new`}>
<Plus className="mr-2 h-4 w-4" />
{createLabel}
</Link>
</Button>
) : (
<Button
type="button"
disabled
className="bg-[#063e8e]/30 text-white hover:bg-[#063e8e]/30"
>
<Plus className="mr-2 h-4 w-4" />
{createLabel}
</Button>
)}
</div>
</div>
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div className="relative w-full max-w-sm">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-700" />
<Input
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder="Tìm kiếm bài viết..."
className="border-[#063e8e]/15 bg-white pl-9 text-gray-700 placeholder:text-gray-700"
/>
</div>
{isSinglePostCategory ? (
<p className="text-sm text-gray-700">Loại danh mục này chỉ giữ 1 bài viết hiển thị.</p>
) : (
<p className="text-sm text-gray-700">
{category.type === 'image'
? 'Bạn có thể thêm nhiều mục nội dung ảnh cho danh mục này.'
: 'Bạn có thể thêm nhiều bài viết cho danh mục này.'}
</p>
)}
</div>
<div className="overflow-hidden rounded-2xl border border-[#063e8e]/15 bg-white shadow-sm">
<Table>
<TableHeader>
<TableRow className="border-0 bg-[#063e8e] hover:bg-[#063e8e]">
<TableHead className="py-4 text-center text-white">Tiêu đề</TableHead>
<TableHead className="w-[180px] py-4 text-center text-white">Slug</TableHead>
<TableHead className="w-[160px] py-4 text-center text-white">Ngày đăng</TableHead>
<TableHead className="w-[130px] py-4 text-center text-white">Hiển thị</TableHead>
<TableHead className="w-[160px] py-4 text-center text-white">Thao tác</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredPosts.length === 0 ? (
<TableRow>
<TableCell colSpan={5} className="py-12 text-center text-sm text-gray-700">
{posts.length === 0
? 'Danh mục này chưa có bài viết nào.'
: 'Không tìm thấy bài viết phù hợp.'}
</TableCell>
</TableRow>
) : (
filteredPosts.map((post, index) => (
<TableRow
key={post.id}
className={index % 2 === 0 ? 'bg-white' : 'bg-[#063e8e]/[0.03]'}
>
<TableCell className="py-4">
<div className="flex items-start gap-4">
<div className="flex h-14 w-20 shrink-0 items-center justify-center overflow-hidden rounded-lg border border-[#063e8e]/10 bg-[#063e8e]/5">
{post.thumbnail ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={post.thumbnail}
alt={post.title}
className="h-full w-full object-cover"
/>
) : (
<ImageIcon className="h-5 w-5 text-[#063e8e]" />
)}
</div>
<div className="min-w-0 space-y-1">
<p className="truncate font-medium text-black">{post.title}</p>
<p className="line-clamp-2 text-sm text-gray-700">{post.excerpt || '—'}</p>
</div>
</div>
</TableCell>
<TableCell className="text-center text-sm text-gray-700">{post.slug}</TableCell>
<TableCell className="text-center text-sm text-gray-700">
{post.published_at ? dayjs(post.published_at).format('DD/MM/YYYY') : '—'}
</TableCell>
<TableCell className="text-center">
{post.is_active ? (
<span className="inline-flex items-center gap-2 text-sm font-medium text-[#063e8e]">
<Eye className="h-4 w-4" />
Hiển thị
</span>
) : (
<span className="inline-flex items-center gap-2 text-sm font-medium text-gray-700">
<EyeOff className="h-4 w-4" />
Ẩn
</span>
)}
</TableCell>
<TableCell className="text-center">
<div className="flex items-center justify-center gap-1">
<Button
variant="ghost"
size="icon"
asChild
className="text-gray-700 hover:bg-[#063e8e]/10 hover:text-[#063e8e]"
>
<Link href={`/admin/header-config/${category.id}/posts/${post.id}`}>
<Pencil className="h-4 w-4" />
</Link>
</Button>
<Button
variant="ghost"
size="icon"
className="text-gray-700 hover:bg-red-50 hover:text-red-600"
onClick={() => setDeleteId(post.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
<AlertDialog open={!!deleteId} onOpenChange={(open) => !open && setDeleteId(null)}>
<AlertDialogContent className="border-[#063e8e]/15 bg-white">
<AlertDialogHeader>
<AlertDialogTitle className="text-[#063e8e]">Xóa bài viết</AlertDialogTitle>
<AlertDialogDescription className="text-gray-700">
Bài viết này sẽ bị xóa khỏi danh mục hiện tại.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel className="border-[#063e8e]/15 bg-white text-gray-700 hover:bg-[#063e8e]/10 hover:text-[#063e8e]">
Hủy
</AlertDialogCancel>
<AlertDialogAction
className="bg-red-600 text-white hover:bg-red-700"
onClick={() => {
if (!deleteId) return;
removePost(deleteId);
toast.success('Đã xóa bài viết');
setDeleteId(null);
}}
>
Xóa
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
"use client";
import * as React from "react";
import { AdminDeleteDialog } from "@/components/admin/admin-delete-dialog";
import { HeaderCategoryTreeItem } from "@/mockdata/header-config";
interface HeaderCategoryDeleteDialogProps {
target: HeaderCategoryTreeItem | null;
open: boolean;
onOpenChange: (open: boolean) => void;
onConfirm: () => void;
}
export function HeaderCategoryDeleteDialog({
target,
open,
onOpenChange,
onConfirm,
}: HeaderCategoryDeleteDialogProps) {
return (
<AdminDeleteDialog
open={open}
title="Xóa danh mục"
description={
target
? `Bạn có chắc chắn muốn xóa "${target.name}"? Tất cả danh mục con trực thuộc cũng sẽ bị xóa.`
: ""
}
onOpenChange={onOpenChange}
onConfirm={onConfirm}
/>
);
}
"use client";
import * as React from "react";
import { Checkbox } from "@/components/ui/checkbox";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import {
headerArticleCategoryOptions,
HeaderCategoryTreeItem,
HeaderCategoryType,
toSlug,
} from "@/mockdata/header-config";
export type HeaderCategoryFormMode = "create" | "edit";
export interface HeaderCategoryFormValues {
id?: string;
name: string;
slug: string;
sort_order: string;
parent_id: string;
type: HeaderCategoryType;
description: string;
category_ids: string[];
}
interface HeaderCategoryFormDialogProps {
mode: HeaderCategoryFormMode;
open: boolean;
values: HeaderCategoryFormValues;
parentOptions: HeaderCategoryTreeItem[];
canChangeParent: boolean;
onOpenChange: (open: boolean) => void;
onValuesChange: React.Dispatch<React.SetStateAction<HeaderCategoryFormValues>>;
onSubmit: () => void;
}
const TYPE_OPTIONS: Array<{ value: HeaderCategoryType; label: string }> = [
{ value: "category", label: "Danh mục" },
{ value: "page", label: "Bài viết trang" },
{ value: "news", label: "Tin tức" },
{ value: "image", label: "Ảnh" },
];
const fieldClassName =
"border-[#063e8e]/15 bg-white text-gray-700 placeholder:text-gray-700 focus-visible:ring-[#063e8e]/30";
const selectTriggerClassName =
"border-[#063e8e]/15 bg-white text-gray-700 data-[placeholder]:text-gray-700 focus:ring-[#063e8e]/30";
const selectContentClassName = "border-[#063e8e]/15 bg-white text-gray-700";
const selectItemClassName = "text-gray-700 focus:bg-[#063e8e]/10 focus:text-[#063e8e]";
export function HeaderCategoryFormDialog({
mode,
open,
values,
parentOptions,
canChangeParent,
onOpenChange,
onValuesChange,
onSubmit,
}: HeaderCategoryFormDialogProps) {
const title = mode === "create" ? "Tạo danh mục" : "Chỉnh sửa danh mục";
const availableTypeOptions = values.parent_id
? TYPE_OPTIONS.filter((option) => option.value !== "category")
: TYPE_OPTIONS;
const setField = <K extends keyof HeaderCategoryFormValues>(
key: K,
value: HeaderCategoryFormValues[K],
) => {
onValuesChange((previous) => ({ ...previous, [key]: value }));
};
const handleNameChange = (value: string) => {
onValuesChange((previous) => ({
...previous,
name: value,
slug: toSlug(value),
}));
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[90vh] max-w-3xl overflow-y-auto border-[#063e8e]/15 bg-white text-gray-700 shadow-xl">
<DialogHeader>
<DialogTitle className="text-[#063e8e]">{title}</DialogTitle>
<DialogDescription className="text-gray-700">
Thiết lập cấu trúc danh mục hiển thị trên header của website.
</DialogDescription>
</DialogHeader>
<div className="grid grid-cols-1 gap-4 py-2 md:grid-cols-2">
<div>
<Label className="mb-1.5 block text-gray-700">Tên danh mục *</Label>
<Input
value={values.name}
onChange={(event) => handleNameChange(event.target.value)}
placeholder="Nhập tên danh mục"
className={fieldClassName}
/>
</div>
<div>
<Label className="mb-1.5 block text-gray-700">Thể loại *</Label>
<Select
value={values.type}
onValueChange={(value) =>
setField("type", value as HeaderCategoryFormValues["type"])
}
>
<SelectTrigger className={selectTriggerClassName}>
<SelectValue />
</SelectTrigger>
<SelectContent className={selectContentClassName}>
{availableTypeOptions.map((option) => (
<SelectItem
key={option.value}
value={option.value}
className={selectItemClassName}
>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label className="mb-1.5 block text-gray-700">Danh mục cha</Label>
<Select
disabled={!canChangeParent}
value={values.parent_id || "__root__"}
onValueChange={(value) =>
setField("parent_id", value === "__root__" ? "" : value)
}
>
<SelectTrigger className={selectTriggerClassName}>
<SelectValue />
</SelectTrigger>
<SelectContent className={selectContentClassName}>
<SelectItem value="__root__" className={selectItemClassName}>
Không có danh mục cha
</SelectItem>
{parentOptions
.filter((item) => item.id !== values.id)
.map((item) => (
<SelectItem
key={item.id}
value={item.id}
className={selectItemClassName}
>
{item.name}
</SelectItem>
))}
</SelectContent>
</Select>
{!canChangeParent ? (
<p className="mt-1 text-xs text-gray-700">
Danh mục đang có danh mục con nên không thể chuyển thành danh mục con.
</p>
) : null}
</div>
<div>
<Label className="mb-1.5 block text-gray-700">Thứ tự</Label>
<Input
type="number"
min="0"
value={values.sort_order}
onChange={(event) => setField("sort_order", event.target.value)}
placeholder="1"
className={fieldClassName}
/>
</div>
<div>
<Label className="mb-1.5 block text-gray-700">Slug</Label>
<Input
value={values.slug}
onChange={(event) => setField("slug", event.target.value)}
placeholder="gioi-thieu"
className={fieldClassName}
/>
</div>
<div className="md:col-span-2">
<Label className="mb-1.5 block text-gray-700">Mô tả</Label>
<Textarea
rows={3}
value={values.description}
onChange={(event) => setField("description", event.target.value)}
placeholder="Mô tả ngắn về danh mục"
className={fieldClassName}
/>
</div>
{values.type === "news" ? (
<div className="md:col-span-2">
<Label className="mb-1.5 block text-gray-700">Thể loại bài viết</Label>
<div className="grid grid-cols-1 gap-2 rounded-lg border border-[#063e8e]/15 p-4 md:grid-cols-2">
{headerArticleCategoryOptions.map((category) => (
<label
key={category.id}
className="flex items-center gap-3 rounded-md border border-[#063e8e]/10 px-3 py-2"
>
<Checkbox
checked={values.category_ids.includes(category.id)}
onCheckedChange={(checked) => {
if (checked) {
setField("category_ids", [...values.category_ids, category.id]);
return;
}
setField(
"category_ids",
values.category_ids.filter((id) => id !== category.id),
);
}}
/>
<span className="text-sm text-gray-700">{category.name}</span>
</label>
))}
</div>
</div>
) : null}
</div>
<DialogFooter>
<Button
variant="outline"
className="border-[#063e8e]/15 bg-white text-gray-700 hover:bg-[#063e8e]/10 hover:text-[#063e8e]"
onClick={() => onOpenChange(false)}
>
Hủy
</Button>
<Button className="bg-[#063e8e] text-white hover:bg-[#063e8e]/90" onClick={onSubmit}>
{mode === "create" ? "Lưu danh mục" : "Cập nhật danh mục"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
"use client";
import * as React from "react";
import { FolderTree } from "lucide-react";
import { AdminStatsGrid } from "@/components/admin/admin-stats-grid";
interface HeaderCategoryStatsProps {
total: number;
root: number;
nested: number;
grouped: number;
}
export function HeaderCategoryStats({
total,
root,
nested,
grouped,
}: HeaderCategoryStatsProps) {
return (
<AdminStatsGrid
items={[
{ label: "Tổng danh mục", value: total, icon: <FolderTree className="h-4 w-4 text-[#063e8e]" /> },
{ label: "Danh mục cha", value: root, icon: <FolderTree className="h-4 w-4 text-[#063e8e]" /> },
{ label: "Danh mục con", value: nested, icon: <FolderTree className="h-4 w-4 text-[#063e8e]" /> },
{ label: "Có danh mục con", value: grouped, icon: <FolderTree className="h-4 w-4 text-[#063e8e]" /> },
]}
/>
);
}
"use client";
import * as React from "react";
import Link from "next/link";
import {
ChevronDown,
ChevronRight,
Edit,
ExternalLink,
FileImage,
FileText,
FolderTree,
MoreHorizontal,
Plus,
Trash,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { HeaderCategoryTreeItem, getHeaderCategoryTypeLabel } from "@/mockdata/header-config";
export type HeaderCategoryFlatRow = HeaderCategoryTreeItem & {
depth: number;
parentId: string | null;
};
interface HeaderCategoryTableProps {
rows: HeaderCategoryFlatRow[];
expanded: Record<string, boolean>;
isLoading: boolean;
searchValue: string;
action?: React.ReactNode;
onSearchChange: (value: string) => void;
onToggle: (id: string) => void;
onCreateChild: (item: HeaderCategoryTreeItem) => void;
onEdit: (item: HeaderCategoryTreeItem) => void;
onDelete: (item: HeaderCategoryTreeItem) => void;
}
function getTypeIcon(type: HeaderCategoryTreeItem["type"]) {
switch (type) {
case "news":
return <FileText className="h-4 w-4 text-[#063e8e]" />;
case "image":
return <FileImage className="h-4 w-4 text-[#063e8e]" />;
default:
return <FolderTree className="h-4 w-4 text-[#063e8e]" />;
}
}
function HeaderCategoryTableLoading() {
return Array.from({ length: 4 }).map((_, index) => (
<TableRow
key={`loading-${index}`}
className={index % 2 === 0 ? "bg-white" : "bg-[#063e8e]/[0.03]"}
>
<TableCell className="w-[34%] py-4">
<div className="flex items-center gap-3">
<Skeleton className="h-4 w-4 rounded-sm bg-[#063e8e]/15" />
<Skeleton className="h-4 w-40 bg-[#063e8e]/15" />
</div>
</TableCell>
<TableCell className="w-[180px] text-center">
<Skeleton className="mx-auto h-7 w-28 rounded-full bg-[#063e8e]/15" />
</TableCell>
<TableCell className="w-[140px] text-center">
<Skeleton className="mx-auto h-8 w-10 rounded-full bg-[#063e8e]/15" />
</TableCell>
<TableCell className="w-[280px] py-4">
<Skeleton className="h-4 w-52 bg-[#063e8e]/15" />
</TableCell>
<TableCell className="w-[120px] text-center">
<Skeleton className="mx-auto h-8 w-8 rounded-md bg-[#063e8e]/15" />
</TableCell>
</TableRow>
));
}
export function HeaderCategoryTable({
rows,
expanded,
isLoading,
searchValue,
action,
onSearchChange,
onToggle,
onCreateChild,
onEdit,
onDelete,
}: HeaderCategoryTableProps) {
return (
<div className="space-y-4">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<Input
value={searchValue}
placeholder="Tìm kiếm danh mục..."
onChange={(event) => onSearchChange(event.target.value)}
className="max-w-sm border-[#063e8e]/15 bg-white text-gray-700 placeholder:text-gray-700"
/>
{action}
</div>
<div className="overflow-hidden rounded-xl border border-[#063e8e]/15 bg-white shadow-sm">
<Table className="table-fixed">
<TableHeader>
<TableRow className="border-0 bg-[#063e8e] hover:bg-[#063e8e]">
<TableHead className="w-[34%] py-4 pl-4 text-center text-white">Tên danh mục</TableHead>
<TableHead className="w-[180px] py-4 text-center text-white">Thể loại</TableHead>
<TableHead className="w-[140px] py-4 text-center text-white">Thứ tự</TableHead>
<TableHead className="w-[280px] py-4 text-center text-white">Liên kết</TableHead>
<TableHead className="w-[120px] py-4 text-center text-white">Thao tác</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoading ? (
<HeaderCategoryTableLoading />
) : rows.length === 0 ? (
<TableRow>
<TableCell colSpan={5} className="py-12 text-center text-sm text-gray-700">
Không có danh mục nào phù hợp.
</TableCell>
</TableRow>
) : (
rows.map((item, index) => {
const hasChildren = rows.some((entry) => entry.parentId === item.id);
const isExpanded = expanded[item.id] ?? true;
const canCreateChild = !item.parent_id && item.type === "category";
const canManagePosts =
item.type === "page" || item.type === "news" || item.type === "image";
const createContentLabel = item.type === "image" ? "Thêm ảnh" : "Thêm bài viết";
return (
<TableRow
key={item.id}
className={index % 2 === 0 ? "bg-white" : "bg-[#063e8e]/[0.03]"}
>
<TableCell className="w-[34%] py-4">
<div className="flex items-center" style={{ marginLeft: item.depth * 24 }}>
{hasChildren ? (
<button
type="button"
className="mr-2 rounded p-1 hover:bg-[#063e8e]/10"
onClick={() => onToggle(item.id)}
>
{isExpanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
</button>
) : (
<span className="mr-2 w-6" />
)}
<div className="mr-2">{getTypeIcon(item.type)}</div>
<div className="truncate font-medium text-black">{item.name}</div>
</div>
</TableCell>
<TableCell className="w-[180px] text-center">
<Badge variant="outline" className="border-[#063e8e]/25 text-[#063e8e]">
{getHeaderCategoryTypeLabel(item.type)}
</Badge>
</TableCell>
<TableCell className="w-[140px] text-center font-medium text-black">
<span
className={
item.parent_id
? "inline-flex min-w-8 items-center justify-center rounded-full border border-gray-300 px-2.5 py-1 text-sm text-gray-700"
: "inline-flex min-w-8 items-center justify-center rounded-full border border-[#063e8e]/20 bg-[#063e8e]/10 px-2.5 py-1 text-sm text-[#063e8e]"
}
>
{item.sort_order}
</span>
</TableCell>
<TableCell className="w-[280px] text-sm text-gray-700">
<div className="mx-auto flex max-w-[220px] items-center justify-center gap-2">
<span className="block max-w-[180px] truncate">{item.static_link || "—"}</span>
{item.static_link ? (
<ExternalLink className="h-3.5 w-3.5 shrink-0 text-[#063e8e]" />
) : null}
</div>
</TableCell>
<TableCell className="w-[120px] text-center">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
className="h-8 w-8 p-0 text-gray-700 hover:bg-[#063e8e]/10 hover:text-[#063e8e]"
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
className="text-gray-700 focus:text-[#063e8e]"
onClick={() => onEdit(item)}
>
<Edit className="mr-2 h-4 w-4" />
Chỉnh sửa
</DropdownMenuItem>
{canManagePosts ? (
<DropdownMenuItem asChild className="text-gray-700 focus:text-[#063e8e]">
<Link href={`/admin/header-config/${item.id}/posts/new`}>
<Plus className="mr-2 h-4 w-4" />
{createContentLabel}
</Link>
</DropdownMenuItem>
) : null}
{canCreateChild ? (
<DropdownMenuItem
className="text-gray-700 focus:text-[#063e8e]"
onClick={() => onCreateChild(item)}
>
<Plus className="mr-2 h-4 w-4" />
Thêm danh mục con
</DropdownMenuItem>
) : null}
<DropdownMenuSeparator />
<DropdownMenuItem
className="text-gray-700 focus:text-[#063e8e]"
onClick={() => onDelete(item)}
>
<Trash className="mr-2 h-4 w-4" />
Xóa
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
</div>
</div>
);
}
export { HeaderCategoryDeleteDialog } from "./header-category-delete-dialog";
export {
HeaderCategoryFormDialog,
type HeaderCategoryFormValues,
type HeaderCategoryFormMode,
} from "./header-category-form-dialog";
export {
HeaderCategoryTable,
type HeaderCategoryFlatRow,
} from "./header-category-table";
export { HeaderCategoryStats } from "./header-category-stats";
'use client';
import React from 'react';
import { Plus } from 'lucide-react';
import { toast } from 'sonner';
import {
HeaderCategoryDeleteDialog,
HeaderCategoryFlatRow,
HeaderCategoryFormDialog,
HeaderCategoryFormValues,
HeaderCategoryFormMode,
HeaderCategoryStats,
HeaderCategoryTable,
} from './components';
import { Button } from '@/components/ui/button';
import {
buildHeaderCategoryTree,
createHeaderCategoryId,
getHeaderCategorySeed,
HEADER_CONFIG_STORAGE_KEY,
HeaderCategoryItem,
HeaderCategoryTreeItem,
normalizeHeaderCategories,
toSlug,
} from '@/mockdata/header-config';
const EMPTY_HEADER_CATEGORY_FORM: HeaderCategoryFormValues = {
name: '',
slug: '',
sort_order: '1',
parent_id: '',
type: 'page',
description: '',
category_ids: [],
};
function toFormValues(item?: HeaderCategoryItem | null): HeaderCategoryFormValues {
if (!item) return EMPTY_HEADER_CATEGORY_FORM;
return {
id: item.id,
name: item.name,
slug: item.slug,
sort_order: String(item.sort_order),
parent_id: item.parent_id ?? '',
type: item.type,
description: item.description ?? '',
category_ids: item.category_ids ?? [],
};
}
function getInitialHeaderConfig() {
if (typeof window === 'undefined') {
return getHeaderCategorySeed();
}
const raw = window.localStorage.getItem(HEADER_CONFIG_STORAGE_KEY);
if (!raw) return getHeaderCategorySeed();
try {
const parsed = JSON.parse(raw) as HeaderCategoryItem[];
if (!Array.isArray(parsed) || parsed.length === 0) {
return getHeaderCategorySeed();
}
return normalizeHeaderCategories(parsed);
} catch {
return getHeaderCategorySeed();
}
}
function persistHeaderConfig(items: HeaderCategoryItem[]) {
if (typeof window === 'undefined') return;
window.localStorage.setItem(
HEADER_CONFIG_STORAGE_KEY,
JSON.stringify(normalizeHeaderCategories(items)),
);
}
function upsertHeaderCategory(items: HeaderCategoryItem[], item: HeaderCategoryItem) {
const exists = items.some((entry) => entry.id === item.id);
const next = exists
? items.map((entry) => (entry.id === item.id ? item : entry))
: [...items, item];
return normalizeHeaderCategories(next);
}
function deleteHeaderCategory(items: HeaderCategoryItem[], id: string) {
const childIds = new Set<string>();
const collect = (targetId: string) => {
childIds.add(targetId);
items
.filter((item) => item.parent_id === targetId)
.forEach((child) => collect(child.id));
};
collect(id);
return normalizeHeaderCategories(items.filter((item) => !childIds.has(item.id)));
}
function useHeaderConfigModule() {
const [items, setItems] = React.useState<HeaderCategoryItem[]>([]);
const [isReady, setIsReady] = React.useState(false);
React.useEffect(() => {
setItems(getInitialHeaderConfig());
setIsReady(true);
}, []);
React.useEffect(() => {
if (!isReady) return;
persistHeaderConfig(items);
}, [isReady, items]);
const tree = React.useMemo(() => buildHeaderCategoryTree(items), [items]);
const createItem = React.useCallback((values: HeaderCategoryFormValues) => {
const nextItem: HeaderCategoryItem = {
id: createHeaderCategoryId(),
name: values.name.trim(),
slug: values.slug.trim() || toSlug(values.name),
static_link: '',
sort_order: Number(values.sort_order) || 1,
type: values.type,
is_article: values.type === 'news',
parent_id: values.parent_id || null,
level: 1,
category_ids: values.type === 'news' ? values.category_ids : [],
description: values.description.trim(),
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
setItems((current) => upsertHeaderCategory(current, nextItem));
}, []);
const updateItem = React.useCallback((values: HeaderCategoryFormValues) => {
if (!values.id) return;
setItems((current) => {
const existing = current.find((item) => item.id === values.id);
if (!existing) return current;
return upsertHeaderCategory(current, {
...existing,
name: values.name.trim(),
slug: values.slug.trim() || toSlug(values.name),
sort_order: Number(values.sort_order) || 1,
type: values.type,
is_article: values.type === 'news',
parent_id: values.parent_id || null,
category_ids: values.type === 'news' ? values.category_ids : [],
description: values.description.trim(),
updated_at: new Date().toISOString(),
});
});
}, []);
const removeItem = React.useCallback((id: string) => {
setItems((current) => deleteHeaderCategory(current, id));
}, []);
return {
tree,
isReady,
createItem,
updateItem,
removeItem,
toFormValues,
};
}
export default function HeaderConfigPage() {
const { tree, isReady, createItem, updateItem, removeItem, toFormValues } =
useHeaderConfigModule();
const [expanded, setExpanded] = React.useState<Record<string, boolean>>({});
const [search, setSearch] = React.useState('');
const [formMode, setFormMode] = React.useState<HeaderCategoryFormMode>('create');
const [formOpen, setFormOpen] = React.useState(false);
const [formValues, setFormValues] = React.useState<HeaderCategoryFormValues>(
EMPTY_HEADER_CATEGORY_FORM,
);
const [deleteTarget, setDeleteTarget] = React.useState<HeaderCategoryTreeItem | null>(null);
React.useEffect(() => {
if (!isReady) return;
setExpanded((previous) => {
const next = { ...previous };
const walk = (items: HeaderCategoryTreeItem[]) => {
items.forEach((item) => {
if (!(item.id in next)) {
next[item.id] = true;
}
if (item.children.length > 0) {
walk(item.children);
}
});
};
walk(tree);
return next;
});
}, [isReady, tree]);
const flatRows = React.useMemo(() => {
const rows: HeaderCategoryFlatRow[] = [];
const walk = (items: HeaderCategoryTreeItem[], depth = 0) => {
items.forEach((item) => {
rows.push({ ...item, depth, parentId: item.parent_id });
if (item.children.length > 0) {
walk(item.children, depth + 1);
}
});
};
walk(tree);
return rows;
}, [tree]);
const visibleRows = React.useMemo(() => {
return flatRows.filter((row) => {
const keyword = search.trim().toLowerCase();
const matchesSearch =
!keyword ||
row.name.toLowerCase().includes(keyword) ||
row.slug.toLowerCase().includes(keyword);
if (!matchesSearch) return false;
if (row.depth === 0) return true;
let parent = row.parentId;
while (parent) {
if (!expanded[parent]) return false;
const parentRow = flatRows.find((entry) => entry.id === parent);
parent = parentRow?.parentId ?? null;
}
return true;
});
}, [expanded, flatRows, search]);
const categoryParentOptions = React.useMemo(
() => tree.filter((item) => item.type === 'category'),
[tree],
);
const groupedCount = React.useMemo(
() => flatRows.filter((item) => item.children.length > 0).length,
[flatRows],
);
const editingItem = React.useMemo(
() => flatRows.find((item) => item.id === formValues.id) ?? null,
[flatRows, formValues.id],
);
const canChangeParent = React.useMemo(() => {
if (!editingItem) return true;
return editingItem.children.length === 0 || !formValues.parent_id;
}, [editingItem, formValues.parent_id]);
const openCreateRoot = () => {
setFormMode('create');
setFormValues(EMPTY_HEADER_CATEGORY_FORM);
setFormOpen(true);
};
const openCreateChild = (item: HeaderCategoryTreeItem) => {
if (item.parent_id || item.type !== 'category') return;
setFormMode('create');
setFormValues({
...EMPTY_HEADER_CATEGORY_FORM,
parent_id: item.id,
sort_order: String(item.children.length + 1),
type: 'page',
});
setExpanded((previous) => ({ ...previous, [item.id]: true }));
setFormOpen(true);
};
const openEdit = (item: HeaderCategoryTreeItem) => {
setFormMode('edit');
setFormValues(toFormValues(item));
setFormOpen(true);
};
const handleSubmit = () => {
if (!formValues.name.trim()) {
toast.error('Tên danh mục là bắt buộc');
return;
}
if (formValues.parent_id) {
const parent = tree.find((item) => item.id === formValues.parent_id);
if (!parent || parent.type !== 'category') {
toast.error('Danh mục cha không hợp lệ');
return;
}
}
if (formValues.parent_id && formValues.type === 'category') {
toast.error('Danh mục con không được có thể loại Danh mục');
return;
}
if (editingItem && editingItem.children.length > 0 && formValues.parent_id) {
toast.error('Danh mục đang có danh mục con nên không thể chuyển thành danh mục con');
return;
}
if (editingItem && editingItem.children.length > 0 && formValues.type !== 'category') {
toast.error('Danh mục đang có danh mục con phải giữ thể loại Danh mục');
return;
}
if (formMode === 'create') {
createItem(formValues);
toast.success('Tạo danh mục thành công');
} else {
updateItem(formValues);
toast.success('Cập nhật danh mục thành công');
}
setFormOpen(false);
setFormValues(EMPTY_HEADER_CATEGORY_FORM);
};
const handleDelete = () => {
if (!deleteTarget) return;
removeItem(deleteTarget.id);
toast.success('Xóa danh mục thành công');
setDeleteTarget(null);
};
return (
<div className="space-y-8">
<HeaderCategoryStats
total={flatRows.length}
root={flatRows.filter((item) => !item.parentId).length}
nested={flatRows.filter((item) => item.parentId).length}
grouped={groupedCount}
/>
<HeaderCategoryTable
rows={visibleRows}
expanded={expanded}
isLoading={!isReady}
searchValue={search}
action={
<Button
className="bg-[#063e8e] text-white hover:bg-[#063e8e]/90"
onClick={openCreateRoot}
>
<Plus className="mr-2 h-4 w-4" />
Thêm danh mục
</Button>
}
onSearchChange={setSearch}
onToggle={(id) =>
setExpanded((previous) => ({ ...previous, [id]: !(previous[id] ?? true) }))
}
onCreateChild={openCreateChild}
onEdit={openEdit}
onDelete={setDeleteTarget}
/>
<HeaderCategoryFormDialog
mode={formMode}
open={formOpen}
values={formValues}
parentOptions={categoryParentOptions}
canChangeParent={canChangeParent}
onOpenChange={setFormOpen}
onValuesChange={setFormValues}
onSubmit={handleSubmit}
/>
<HeaderCategoryDeleteDialog
target={deleteTarget}
open={!!deleteTarget}
onOpenChange={(open) => {
if (!open) {
setDeleteTarget(null);
}
}}
onConfirm={handleDelete}
/>
</div>
);
}
'use client';
import React from 'react';
import { AdminSidebar } from '@/components/shared/admin-sidebar';
import { AdminHeader } from '@/components/shared/admin-header';
import { useSidebarStore } from '@/hooks/use-admin-sidebar';
import { cn } from '@/lib/utils';
export default function AdminLayout({ children }: { children: React.ReactNode }) {
const { isOpen } = useSidebarStore();
return (
<div className="min-h-screen bg-white">
<AdminSidebar />
<div
className={cn(
'transition-all duration-300',
isOpen ? 'pl-56' : 'pl-20',
)}
>
<AdminHeader />
<main className="px-4 py-4 lg:px-6 lg:py-6">{children}</main>
</div>
</div>
);
}
'use client';
import React, { useState } from 'react';
import {
useGetOrganizations,
getGetOrganizationsQueryKey,
} from '@/api/endpoints/organizations';
import { useQueryClient } from '@tanstack/react-query';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Search, ExternalLink } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import dayjs from 'dayjs';
export default function MembersPage() {
const [search, setSearch] = useState('');
const [page, setPage] = useState(1);
const pageSize = 20;
const { data, isLoading } = useGetOrganizations({
currentPage: String(page),
pageSize: String(pageSize),
filters: search ? `name@=${search}` : undefined,
});
const rows = (data as any)?.responseData?.rows ?? (data as any)?.data?.rows ?? [];
const total = (data as any)?.responseData?.count ?? (data as any)?.data?.count ?? 0;
const totalPages = Math.ceil(total / pageSize);
return (
<div>
<div className="flex items-center justify-between mb-6">
<div>
<h2 className="text-xl font-bold text-gray-800">Quản lý Hội viên</h2>
<p className="text-sm text-gray-500 mt-1">
Danh sách tất cả tổ chức / doanh nghiệp hội viên.
</p>
</div>
<Badge variant="outline" className="border-[#063e8e]/30 text-[#063e8e] text-sm px-3 py-1">
{total} hội viên
</Badge>
</div>
<div className="relative w-72 mb-4">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
<Input
className="pl-9"
placeholder="Tìm theo tên..."
value={search}
onChange={(e) => { setSearch(e.target.value); setPage(1); }}
/>
</div>
<div className="bg-white rounded-lg border shadow-sm overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-8">#</TableHead>
<TableHead>Tên tổ chức</TableHead>
<TableHead>Mã số thuế</TableHead>
<TableHead>Email</TableHead>
<TableHead>Địa chỉ</TableHead>
<TableHead className="w-24">Trạng thái</TableHead>
<TableHead>Ngày tạo</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoading ? (
Array.from({ length: 5 }).map((_, i) => (
<TableRow key={i}>
{Array.from({ length: 7 }).map((_, j) => (
<TableCell key={j}><Skeleton className="h-4 w-full" /></TableCell>
))}
</TableRow>
))
) : rows.length === 0 ? (
<TableRow>
<TableCell colSpan={7} className="text-center text-gray-400 py-10 text-sm">
Chưa có hội viên nào.
</TableCell>
</TableRow>
) : rows.map((org: any, idx: number) => (
<TableRow key={org.id ?? idx}>
<TableCell className="text-gray-400 text-sm">{(page - 1) * pageSize + idx + 1}</TableCell>
<TableCell>
<div className="flex items-center gap-3">
<Avatar className="h-8 w-8 shrink-0">
<AvatarImage src={org.avatar} alt={org.name} />
<AvatarFallback className="bg-[#063e8e]/10 text-[#063e8e] text-xs font-bold">
{org.name?.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="min-w-0">
<p className="font-medium text-sm truncate max-w-[200px]">{org.name}</p>
{org.website && (
<a
href={org.website}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1 text-xs text-blue-500 hover:underline"
>
<ExternalLink size={10} />{org.website.replace(/^https?:\/\//, '')}
</a>
)}
</div>
</div>
</TableCell>
<TableCell className="text-sm text-gray-600">{org.tax_code || '—'}</TableCell>
<TableCell className="text-sm text-gray-600">{org.org_email || '—'}</TableCell>
<TableCell className="text-sm text-gray-500 max-w-40 truncate">{org.address || '—'}</TableCell>
<TableCell>
{org.is_premium ? (
<Badge className="bg-amber-500/10 text-amber-600 border-amber-200 text-xs">Premium</Badge>
) : (
<Badge variant="outline" className="text-gray-500 text-xs">Thường</Badge>
)}
</TableCell>
<TableCell className="text-gray-400 text-sm">
{org.created_at ? dayjs(org.created_at).format('DD/MM/YYYY') : '—'}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
{totalPages > 1 && (
<div className="flex justify-end gap-2 mt-4">
<Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>Trước</Button>
<span className="text-sm text-gray-500 self-center">{page} / {totalPages}</span>
<Button variant="outline" size="sm" disabled={page >= totalPages} onClick={() => setPage((p) => p + 1)}>Sau</Button>
</div>
)}
</div>
);
}
'use client';
import React, { useEffect, useState, useTransition } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import {
useGetNewsId,
usePostNews,
usePutNewsId,
getGetNewsAdminQueryKey,
} from '@/api/endpoints/news';
import { useGetCategory } from '@/api/endpoints/category';
import { useGetNewsPageConfigGetHierarchical } from '@/api/endpoints/news-page-config';
import { GetCategoryAdminResponseType } from '@/api/types/category';
import {
GetNewsPageConfigResponseType,
NewsPageConfigItem,
} from '@/api/types/news-page-config';
import { useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { ArrowLeft, Save } from 'lucide-react';
import { Spinner } from '@/components/ui';
// Flatten news page config tree for select options
function flattenTree(
node: NewsPageConfigItem,
depth = 0,
): { id: string; label: string }[] {
const prefix = ' '.repeat(depth);
const self = { id: node.id, label: `${prefix}${node.name}` };
const children = (node.children ?? []).flatMap((c) => flattenTree(c, depth + 1));
return [self, ...children];
}
export default function NewsFormPage() {
const params = useParams();
const router = useRouter();
const qc = useQueryClient();
const id = params?.id as string;
const isNew = id === 'new';
const [, startTransition] = useTransition();
const [form, setForm] = useState({
title: '',
thumbnail: '',
external_link: '',
description: '',
release_at: '',
is_active: true,
category: '',
page_config_id: '',
});
// Fetch existing news when editing
const { data: newsData, isLoading: newsLoading } = useGetNewsId(isNew ? '' : id, {
query: { enabled: !isNew && !!id },
});
useEffect(() => {
const d = (newsData as Record<string, unknown>)?.responseData as Record<string, unknown> | undefined
?? (newsData as Record<string, unknown>)?.data as Record<string, unknown> | undefined;
if (!d) return;
// Intentional: populate form when data loads
startTransition(() => setForm({
title: (d.title as string) ?? '',
thumbnail: (d.thumbnail as string) ?? '',
external_link: (d.external_link as string) ?? '',
description: (d.description as string) ?? '',
release_at: d.release_at ? (d.release_at as string).slice(0, 10) : '',
is_active: (d.is_active as boolean) ?? true,
category: (d.category as string) ?? '',
page_config_id: ((d.page_config as Record<string, string>)?.id) ?? (d.page_config_id as string) ?? '',
}));
}, [newsData]);
// Categories
const { data: catData } = useGetCategory<GetCategoryAdminResponseType>({ pageSize: '100' });
const categories = catData?.responseData?.rows ?? [];
// Page config tree
const { data: configData } = useGetNewsPageConfigGetHierarchical<GetNewsPageConfigResponseType>();
const configRoot = configData?.responseData;
const configOptions = configRoot ? flattenTree(configRoot) : [];
// Mutations
const { mutate: create, isPending: creating } = usePostNews({
mutation: {
onSuccess: () => {
qc.invalidateQueries({ queryKey: getGetNewsAdminQueryKey() });
router.push('/admin/news');
},
},
});
const { mutate: update, isPending: updating } = usePutNewsId({
mutation: {
onSuccess: () => {
qc.invalidateQueries({ queryKey: getGetNewsAdminQueryKey() });
router.push('/admin/news');
},
},
});
const isPending = creating || updating;
const setField = <K extends keyof typeof form>(key: K, value: (typeof form)[K]) => {
setForm((prev) => ({ ...prev, [key]: value }));
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const payload = {
title: form.title,
thumbnail: form.thumbnail || undefined,
external_link: form.external_link || undefined,
description: form.description,
release_at: form.release_at || undefined,
is_active: form.is_active,
category: form.category || undefined,
page_config_id: form.page_config_id || undefined,
};
if (isNew) {
create({ data: [payload] });
} else {
update({ id, data: payload });
}
};
if (!isNew && newsLoading) {
return (
<div className="flex justify-center py-20">
<Spinner />
</div>
);
}
return (
<div className="max-w-2xl">
<div className="flex items-center gap-3 mb-6">
<Button variant="ghost" size="icon" asChild>
<Link href="/admin/news">
<ArrowLeft size={18} />
</Link>
</Button>
<div>
<h2 className="text-xl font-bold text-gray-800">
{isNew ? 'Thêm bài viết mới' : 'Chỉnh sửa bài viết'}
</h2>
<p className="text-sm text-gray-500 mt-0.5">
{isNew ? 'Điền thông tin để tạo bài viết mới.' : `Đang sửa bài viết #${id}`}
</p>
</div>
</div>
<form onSubmit={handleSubmit} className="bg-white rounded-lg border shadow-sm p-6 space-y-5">
{/* Title */}
<div className="space-y-1.5">
<Label htmlFor="title">Tiêu đề *</Label>
<Input
id="title"
required
value={form.title}
onChange={(e) => setField('title', e.target.value)}
placeholder="Nhập tiêu đề bài viết..."
/>
</div>
{/* Thumbnail */}
<div className="space-y-1.5">
<Label htmlFor="thumbnail">URL ảnh thumbnail</Label>
<Input
id="thumbnail"
value={form.thumbnail}
onChange={(e) => setField('thumbnail', e.target.value)}
placeholder="https://..."
/>
{form.thumbnail && (
// eslint-disable-next-line @next/next/no-img-element
<img
src={form.thumbnail}
alt="preview"
className="mt-2 h-32 w-auto rounded-md border object-cover"
onError={(e) => { (e.currentTarget as HTMLImageElement).style.display = 'none'; }}
/>
)}
</div>
{/* External link */}
<div className="space-y-1.5">
<Label htmlFor="ext-link">Đường dẫn ngoài (nếu có)</Label>
<Input
id="ext-link"
value={form.external_link}
onChange={(e) => setField('external_link', e.target.value)}
placeholder="https://..."
/>
</div>
{/* Category */}
<div className="space-y-1.5">
<Label>Thể loại</Label>
<Select value={form.category} onValueChange={(v) => setField('category', v)}>
<SelectTrigger>
<SelectValue placeholder="Chọn thể loại..." />
</SelectTrigger>
<SelectContent>
{categories.map((cat) => (
<SelectItem key={cat.id} value={cat.id}>
{cat.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Page config */}
<div className="space-y-1.5">
<Label>Danh mục menu (page config)</Label>
<Select value={form.page_config_id} onValueChange={(v) => setField('page_config_id', v)}>
<SelectTrigger>
<SelectValue placeholder="Chọn danh mục..." />
</SelectTrigger>
<SelectContent className="max-h-60">
{configOptions.map((opt) => (
<SelectItem key={opt.id} value={opt.id}>
{opt.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Release date */}
<div className="space-y-1.5">
<Label htmlFor="release-at">Ngày đăng</Label>
<Input
id="release-at"
type="date"
value={form.release_at}
onChange={(e) => setField('release_at', e.target.value)}
/>
</div>
{/* Description */}
<div className="space-y-1.5">
<Label htmlFor="desc">Nội dung / Mô tả (HTML)</Label>
<Textarea
id="desc"
value={form.description}
onChange={(e) => setField('description', e.target.value)}
placeholder="<p>Nội dung bài viết...</p>"
rows={8}
className="font-mono text-sm"
/>
</div>
{/* Is active */}
<div className="flex items-center gap-3">
<Switch
id="is-active"
checked={form.is_active}
onCheckedChange={(v) => setField('is_active', v)}
/>
<Label htmlFor="is-active" className="cursor-pointer">
Hiển thị bài viết
</Label>
</div>
{/* Submit */}
<div className="flex justify-end gap-3 pt-2">
<Button variant="outline" type="button" asChild>
<Link href="/admin/news">Huỷ</Link>
</Button>
<Button type="submit" disabled={isPending}>
<Save size={15} className="mr-1" />
{isPending ? 'Đang lưu...' : isNew ? 'Tạo bài viết' : 'Cập nhật'}
</Button>
</div>
</form>
</div>
);
}
'use client';
import React, { useState } from 'react';
import Link from 'next/link';
import {
useGetNewsAdmin,
useDeleteNewsId,
getGetNewsAdminQueryKey,
} from '@/api/endpoints/news';
import { GetNewsResponseType } from '@/api/types/news';
import { useQueryClient } from '@tanstack/react-query';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Eye, EyeOff, Pencil, Plus, Search, Trash2 } from 'lucide-react';
import dayjs from 'dayjs';
import { Spinner } from '@/components/ui';
function DeleteConfirm({ item, onClose }: { item: { id: string; title: string }; onClose: () => void }) {
const qc = useQueryClient();
const { mutate: del, isPending } = useDeleteNewsId({
mutation: {
onSuccess: () => {
qc.invalidateQueries({ queryKey: getGetNewsAdminQueryKey() });
onClose();
},
},
});
return (
<AlertDialog open onOpenChange={() => onClose()}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Xoá bài viết?</AlertDialogTitle>
<AlertDialogDescription>
Bài viết <strong>"{item.title}"</strong> sẽ bị xoá vĩnh viễn.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Huỷ</AlertDialogCancel>
<AlertDialogAction
className="bg-red-600 hover:bg-red-700"
onClick={() => del({ id: String(item.id) })}
disabled={isPending}
>
{isPending ? 'Đang xoá...' : 'Xoá'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
export default function NewsPage() {
const [search, setSearch] = useState('');
const [page, setPage] = useState(1);
const [deleteItem, setDeleteItem] = useState<{ id: string; title: string } | null>(null);
const pageSize = 20;
const { data, isLoading } = useGetNewsAdmin<GetNewsResponseType>({
currentPage: String(page),
pageSize: String(pageSize),
filters: search ? `title@=${search}` : undefined,
});
const rows = data?.responseData?.rows ?? [];
const totalPages = data?.responseData?.totalPages ?? 1;
return (
<div>
<div className="flex items-center justify-between mb-6">
<div>
<h2 className="text-xl font-bold text-gray-800">Danh sách bài viết</h2>
<p className="text-sm text-gray-500 mt-1">Tất cả bài viết trong hệ thống.</p>
</div>
<Button asChild>
<Link href="/admin/news/new">
<Plus size={16} className="mr-1" /> Thêm bài viết
</Link>
</Button>
</div>
<div className="relative w-72 mb-4">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
<Input
className="pl-9"
placeholder="Tìm kiếm tiêu đề..."
value={search}
onChange={(e) => { setSearch(e.target.value); setPage(1); }}
/>
</div>
<div className="bg-white rounded-lg border shadow-sm overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-8">#</TableHead>
<TableHead>Tiêu đề</TableHead>
<TableHead>Thể loại</TableHead>
<TableHead>Danh mục</TableHead>
<TableHead className="w-16 text-center">Hiển thị</TableHead>
<TableHead>Ngày đăng</TableHead>
<TableHead className="w-24 text-right">Thao tác</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoading ? (
<TableRow>
<TableCell colSpan={7} className="text-center py-10"><Spinner /></TableCell>
</TableRow>
) : rows.length === 0 ? (
<TableRow>
<TableCell colSpan={7} className="text-center text-gray-400 py-10 text-sm">Chưa có bài viết nào.</TableCell>
</TableRow>
) : rows.map((news: Record<string, any>, idx: number) => (
<TableRow key={news.id}>
<TableCell className="text-gray-400 text-sm">{(page - 1) * pageSize + idx + 1}</TableCell>
<TableCell className="max-w-xs">
<p className="font-medium text-sm truncate">{news.title}</p>
{news.external_link && (
<p className="text-xs text-blue-400 truncate">{news.external_link}</p>
)}
</TableCell>
<TableCell>
{news.category?.name ? (
<Badge variant="secondary" className="text-xs">{news.category.name}</Badge>
) : <span className="text-gray-300 text-xs"></span>}
</TableCell>
<TableCell className="text-sm text-gray-500 max-w-[120px] truncate">
{news.pageConfig?.name || '—'}
</TableCell>
<TableCell className="text-center">
{news.is_active ? (
<Eye size={16} className="inline text-green-500" />
) : (
<EyeOff size={16} className="inline text-gray-300" />
)}
</TableCell>
<TableCell className="text-gray-400 text-sm">
{news.release_at ? dayjs(news.release_at).format('DD/MM/YYYY') : '—'}
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-1">
<Button size="icon" variant="ghost" asChild>
<Link href={`/admin/news/${news.id}`}><Pencil size={15} /></Link>
</Button>
<Button
size="icon"
variant="ghost"
className="text-red-500 hover:text-red-600"
onClick={() => setDeleteItem({ id: String(news.id), title: String(news.title) })}
>
<Trash2 size={15} />
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
{totalPages > 1 && (
<div className="flex justify-end gap-2 mt-4">
<Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>Trước</Button>
<span className="text-sm text-gray-500 self-center">{page} / {totalPages}</span>
<Button variant="outline" size="sm" disabled={page >= totalPages} onClick={() => setPage((p) => p + 1)}>Sau</Button>
</div>
)}
{deleteItem && <DeleteConfirm item={deleteItem} onClose={() => setDeleteItem(null)} />}
</div>
);
}
import { redirect } from 'next/navigation';
export default function AdminPage() {
redirect('/admin/dashboard');
}
'use client';
import React, { useState } from 'react';
import { useGetOrganizations } from '@/api/endpoints/organizations';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Search, ExternalLink } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import dayjs from 'dayjs';
export default function PartnersPage() {
const [search, setSearch] = useState('');
const [page, setPage] = useState(1);
const pageSize = 20;
// Filter by type = "PARTNER" or use org categories — using filters param
const { data, isLoading } = useGetOrganizations({
currentPage: String(page),
pageSize: String(pageSize),
filters: search ? `name@=${search}` : undefined,
// note: filter by partner type when backend supports it
});
const rows = (data as any)?.responseData?.rows ?? (data as any)?.data?.rows ?? [];
const total = (data as any)?.responseData?.count ?? (data as any)?.data?.count ?? 0;
const totalPages = Math.ceil(total / pageSize);
return (
<div>
<div className="flex items-center justify-between mb-6">
<div>
<h2 className="text-xl font-bold text-gray-800">Quản lý Đối tác</h2>
<p className="text-sm text-gray-500 mt-1">
Danh sách tổ chức / đối tác liên kết với VCCI.
</p>
</div>
<Badge variant="outline" className="border-[#063e8e]/30 text-[#063e8e] text-sm px-3 py-1">
{total} đối tác
</Badge>
</div>
<div className="relative w-72 mb-4">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
<Input
className="pl-9"
placeholder="Tìm theo tên đối tác..."
value={search}
onChange={(e) => { setSearch(e.target.value); setPage(1); }}
/>
</div>
<div className="bg-white rounded-lg border shadow-sm overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-8">#</TableHead>
<TableHead>Tên tổ chức</TableHead>
<TableHead>Mã số thuế</TableHead>
<TableHead>Website</TableHead>
<TableHead>Email</TableHead>
<TableHead>Địa chỉ</TableHead>
<TableHead>Ngày tạo</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoading ? (
Array.from({ length: 5 }).map((_, i) => (
<TableRow key={i}>
{Array.from({ length: 7 }).map((_, j) => (
<TableCell key={j}><Skeleton className="h-4 w-full" /></TableCell>
))}
</TableRow>
))
) : rows.length === 0 ? (
<TableRow>
<TableCell colSpan={7} className="text-center text-gray-400 py-10 text-sm">
Chưa có đối tác nào.
</TableCell>
</TableRow>
) : rows.map((org: any, idx: number) => (
<TableRow key={org.id ?? idx}>
<TableCell className="text-gray-400 text-sm">{(page - 1) * pageSize + idx + 1}</TableCell>
<TableCell>
<div className="flex items-center gap-3">
<Avatar className="h-8 w-8 shrink-0">
<AvatarImage src={org.avatar} alt={org.name} />
<AvatarFallback className="bg-violet-100 text-violet-700 text-xs font-bold">
{org.name?.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<p className="font-medium text-sm truncate max-w-[200px]">{org.name}</p>
</div>
</TableCell>
<TableCell className="text-sm text-gray-600">{org.tax_code || '—'}</TableCell>
<TableCell>
{org.website ? (
<a
href={org.website}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1 text-xs text-blue-500 hover:underline"
>
<ExternalLink size={12} />
{org.website.replace(/^https?:\/\//, '')}
</a>
) : <span className="text-gray-300 text-sm"></span>}
</TableCell>
<TableCell className="text-sm text-gray-600">{org.org_email || '—'}</TableCell>
<TableCell className="text-sm text-gray-500 max-w-[140px] truncate">{org.address || '—'}</TableCell>
<TableCell className="text-gray-400 text-sm">
{org.created_at ? dayjs(org.created_at).format('DD/MM/YYYY') : '—'}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
{totalPages > 1 && (
<div className="flex justify-end gap-2 mt-4">
<Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>Trước</Button>
<span className="text-sm text-gray-500 self-center">{page} / {totalPages}</span>
<Button variant="outline" size="sm" disabled={page >= totalPages} onClick={() => setPage((p) => p + 1)}>Sau</Button>
</div>
)}
</div>
);
}
'use client';
import React, { useEffect, useState } from 'react';
import {
useGetConfig,
usePutConfig,
getGetConfigQueryKey,
} from '@/api/endpoints/website-config';
import { WebConfig } from '@/api/models/webConfig';
import { useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';
import { Save, Globe, Phone, Mail, MapPin, Link as LinkIcon } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { toast } from 'sonner';
export default function WebsiteConfigPage() {
const qc = useQueryClient();
const { data, isLoading } = useGetConfig({});
const config: WebConfig | undefined =
(data as any)?.responseData ?? (data as any)?.data ?? undefined;
const [form, setForm] = useState<WebConfig>({
name: '',
name_en: '',
address: '',
address_en: '',
logo: '',
link: '',
phone: '',
email: '',
social: '',
});
useEffect(() => {
if (config) {
setForm({
name: config.name ?? '',
name_en: config.name_en ?? '',
address: config.address ?? '',
address_en: config.address_en ?? '',
logo: config.logo ?? '',
link: config.link ?? '',
phone: config.phone ?? '',
email: config.email ?? '',
social: config.social ?? '',
});
}
}, [config]);
const { mutate: save, isPending } = usePutConfig({
mutation: {
onSuccess: () => {
qc.invalidateQueries({ queryKey: getGetConfigQueryKey() });
toast.success('Đã lưu thông tin website!');
},
onError: () => {
toast.error('Có lỗi khi lưu thông tin. Vui lòng thử lại.');
},
},
});
const setField = <K extends keyof WebConfig>(key: K, value: WebConfig[K]) => {
setForm((prev) => ({ ...prev, [key]: value }));
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!config?.id) return;
save({ params: { filters: String(config.id) }, data: form });
};
return (
<div className="max-w-2xl space-y-6">
<div>
<h2 className="text-xl font-bold text-gray-800">Thông tin website</h2>
<p className="text-sm text-gray-500 mt-1">
Cập nhật thông tin chung hiển thị trên website VCCI News.
</p>
</div>
{isLoading ? (
<div className="space-y-4">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="space-y-1.5">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-10 w-full" />
</div>
))}
</div>
) : (
<form onSubmit={handleSubmit} className="space-y-6">
{/* Tên website */}
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Globe className="h-4 w-4 text-[#063e8e]" /> Tên & Logo
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<Label htmlFor="name">Tên (Tiếng Việt)</Label>
<Input
id="name"
value={form.name}
onChange={(e) => setField('name', e.target.value)}
placeholder="VCCI HCM"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="name_en">Tên (Tiếng Anh)</Label>
<Input
id="name_en"
value={form.name_en}
onChange={(e) => setField('name_en', e.target.value)}
placeholder="VCCI HCM (English)"
/>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="logo">URL Logo</Label>
<div className="flex gap-3 items-start">
<Input
id="logo"
value={form.logo}
onChange={(e) => setField('logo', e.target.value)}
placeholder="https://..."
className="flex-1"
/>
{form.logo && (
<img
src={form.logo}
alt="logo preview"
className="h-10 w-auto border rounded object-contain"
onError={(e) => { (e.currentTarget as HTMLImageElement).style.display = 'none'; }}
/>
)}
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="link">
<LinkIcon className="inline h-3.5 w-3.5 mr-1" />
Đường dẫn website
</Label>
<Input
id="link"
value={form.link}
onChange={(e) => setField('link', e.target.value)}
placeholder="https://vccihn.com"
/>
</div>
</CardContent>
</Card>
<Separator />
{/* Liên hệ */}
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Phone className="h-4 w-4 text-[#063e8e]" /> Thông tin liên hệ
</CardTitle>
<CardDescription className="text-xs">Hiển thị ở footer và trang liên hệ.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<Label htmlFor="phone">
<Phone className="inline h-3.5 w-3.5 mr-1" />
Điện thoại
</Label>
<Input
id="phone"
value={form.phone}
onChange={(e) => setField('phone', e.target.value)}
placeholder="028 xxxx xxxx"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="email">
<Mail className="inline h-3.5 w-3.5 mr-1" />
Email
</Label>
<Input
id="email"
type="email"
value={form.email}
onChange={(e) => setField('email', e.target.value)}
placeholder="info@vcci.com.vn"
/>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="address">
<MapPin className="inline h-3.5 w-3.5 mr-1" />
Địa chỉ (Tiếng Việt)
</Label>
<Input
id="address"
value={form.address}
onChange={(e) => setField('address', e.target.value)}
placeholder="171 Võ Thị Sáu, Quận 3, TP.HCM"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="address_en">
<MapPin className="inline h-3.5 w-3.5 mr-1" />
Địa chỉ (Tiếng Anh)
</Label>
<Input
id="address_en"
value={form.address_en}
onChange={(e) => setField('address_en', e.target.value)}
placeholder="171 Vo Thi Sau, District 3, HCMC"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="social">Mạng xã hội (URL Facebook / Fanpage)</Label>
<Input
id="social"
value={form.social}
onChange={(e) => setField('social', e.target.value)}
placeholder="https://facebook.com/vccihn"
/>
</div>
</CardContent>
</Card>
<div className="flex justify-end">
<Button type="submit" disabled={isPending || !config?.id} className="bg-[#063e8e] hover:bg-[#063e8e]/90">
<Save size={15} className="mr-2" />
{isPending ? 'Đang lưu...' : 'Lưu thay đổi'}
</Button>
</div>
</form>
)}
</div>
);
}
"use client";
import * as React from "react";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
interface AdminDeleteDialogProps {
open: boolean;
title: string;
description: React.ReactNode;
confirmLabel?: string;
cancelLabel?: string;
onOpenChange: (open: boolean) => void;
onConfirm: () => void;
}
export function AdminDeleteDialog({
open,
title,
description,
confirmLabel = "Xóa",
cancelLabel = "Hủy",
onOpenChange,
onConfirm,
}: AdminDeleteDialogProps) {
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{title}</AlertDialogTitle>
<AlertDialogDescription>{description}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{cancelLabel}</AlertDialogCancel>
<AlertDialogAction className="bg-[#063e8e] hover:bg-[#063e8e]/90" onClick={onConfirm}>
{confirmLabel}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
"use client";
import * as React from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
interface AdminStatsGridItem {
label: string;
value: number | string;
icon?: React.ReactNode;
}
interface AdminStatsGridProps {
items: AdminStatsGridItem[];
className?: string;
}
export function AdminStatsGrid({ items, className }: AdminStatsGridProps) {
return (
<div className={className ?? "grid grid-cols-2 gap-4 lg:grid-cols-4"}>
{items.map((item) => (
<Card key={item.label} className="border-slate-200 shadow-sm">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-gray-700">
{item.label}
</CardTitle>
{item.icon ?? null}
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-black">{item.value}</div>
</CardContent>
</Card>
))}
</div>
);
}
'use client';
import React from 'react';
import { usePathname } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { useSidebarStore } from '@/hooks/use-admin-sidebar';
import { Menu } from 'lucide-react';
const routeLabels: Record<string, string> = {
'/admin/dashboard': 'Dashboard',
'/admin/header-config': 'Cấu hình Danh mục',
'/admin/news': 'Quản lý bài viết',
'/admin/members': 'Quản lý Hội viên',
'/admin/partners': 'Quản lý Đối tác',
'/admin/emails': 'Email nhận thông tin',
'/admin/website-config': 'Thông tin website',
};
function getTitle(pathname: string): string {
if (routeLabels[pathname]) return routeLabels[pathname];
for (const [prefix, label] of Object.entries(routeLabels)) {
if (pathname.startsWith(prefix + '/')) return label;
}
return 'Quản trị';
}
export function AdminHeader() {
const { toggle } = useSidebarStore();
const pathname = usePathname();
const title = getTitle(pathname);
return (
<header className="sticky top-0 z-30 border-b border-[#063e8e]/15 bg-background/95 shadow-sm backdrop-blur supports-backdrop-filter:bg-background/80">
<div className="flex h-16 items-center justify-between px-4 lg:px-6">
<div className="flex items-center gap-4">
<Button
variant="ghost"
size="icon"
onClick={toggle}
className="text-[#063e8e]"
title="Toggle sidebar"
>
<Menu className="h-5 w-5" />
</Button>
<h1 className="text-xl font-bold text-[#063e8e]">{title}</h1>
</div>
<div className="flex items-center gap-2 text-xs text-gray-500">
Cập nhật: {new Date().toLocaleDateString('vi-VN')}
</div>
</div>
</header>
);
}
'use client';
import React from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import {
BarChart3,
Building2,
ChevronDown,
Globe,
Layers,
Mail,
Newspaper,
Settings,
Users,
} from 'lucide-react';
import logo from '@/assets/VCCI-HCM-logo-VN-2025.png';
import { useSidebarStore } from '@/hooks/use-admin-sidebar';
import { cn } from '@/lib/utils';
type NavChild = { name: string; href: string };
type NavItem = {
name: string;
icon: React.ComponentType<{ className?: string }>;
href?: string;
children?: NavChild[];
};
const navigation: NavItem[] = [
{ name: 'Dashboard', href: '/admin/dashboard', icon: BarChart3 },
{ name: 'Cấu hình danh mục', href: '/admin/header-config', icon: Layers },
{ name: 'Quản lý bài viết', href: '/admin/news', icon: Newspaper },
{ name: 'Quản lý hội viên', href: '/admin/members', icon: Users },
{ name: 'Quản lý đối tác', href: '/admin/partners', icon: Building2 },
{ name: 'Email thông tin', href: '/admin/emails', icon: Mail },
{
name: 'Thiết lập',
icon: Settings,
children: [{ name: 'Thông tin website', href: '/admin/website-config' }],
},
];
export function AdminSidebar() {
const pathname = usePathname();
const { isOpen } = useSidebarStore();
const [expandedGroups, setExpandedGroups] = React.useState<Record<string, boolean>>({
'Thiết lập': true,
});
const isItemActive = (href: string) => pathname === href || pathname.startsWith(`${href}/`);
const isGroupActive = (children: NavChild[]) => children.some((child) => isItemActive(child.href));
const toggleGroup = (name: string) =>
setExpandedGroups((previous) => ({ ...previous, [name]: !previous[name] }));
return (
<aside
className={cn(
'fixed left-0 top-0 z-40 h-screen border-r border-[#063e8e]/15 bg-[#063e8e]/20 shadow-[0_10px_30px_rgba(6,62,142,0.08)] transition-all duration-300',
isOpen ? 'w-56' : 'w-20',
)}
>
<div className="flex h-full flex-col">
<div
className={cn(
'flex h-16 items-center border-b border-[#063e8e]/12 bg-white/80 px-4 backdrop-blur-sm',
!isOpen && 'justify-center px-2.5',
)}
>
<Link
href="/admin/dashboard"
className={cn('flex min-w-0 items-center gap-3', isOpen && 'justify-start')}
>
<div
className={cn(
'flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-[#063e8e]/12 bg-white p-1.5 shadow-sm',
!isOpen && 'h-10 w-10',
)}
>
<Image
src={logo}
alt="VCCI HCM"
className="h-full w-full object-contain"
priority
/>
</div>
{isOpen ? (
<div className="min-w-0 leading-tight">
<div className="truncate text-sm font-semibold uppercase tracking-[0.18em] text-[#063e8e]">
VCCI News
</div>
<div className="mt-1 truncate text-[11px] text-gray-700">
Trang quản trị website
</div>
</div>
) : null}
</Link>
</div>
<nav className={cn('flex-1 space-y-2 overflow-y-auto px-3 py-4', !isOpen && 'px-2')}>
{navigation.map((item) => {
if (item.children) {
const active = isGroupActive(item.children);
const expanded = expandedGroups[item.name] ?? active;
return (
<div key={item.name} className="space-y-2">
<button
type="button"
onClick={() => isOpen && toggleGroup(item.name)}
className={cn(
'group flex w-full items-center rounded-2xl px-3 py-3 text-sm font-medium transition-all duration-200',
active
? 'bg-[#063e8e] text-white shadow-[0_12px_24px_rgba(6,62,142,0.16)]'
: 'text-gray-700 hover:bg-[#063e8e]/8 hover:text-[#063e8e]',
!isOpen && 'justify-center px-0',
)}
>
<item.icon className="h-5 w-5 shrink-0" />
{isOpen ? (
<>
<span className="ml-3 truncate text-left">{item.name}</span>
<ChevronDown
className={cn('ml-auto h-4 w-4 transition-transform', expanded && 'rotate-180')}
/>
</>
) : null}
</button>
{isOpen && expanded ? (
<div className="ml-4 space-y-1.5 border-l border-[#063e8e]/12 pl-4">
{item.children.map((child) => {
const childActive = isItemActive(child.href);
return (
<Link
key={child.name}
href={child.href}
className={cn(
'block rounded-xl px-3 py-2.5 text-sm transition-colors',
childActive
? 'bg-[#063e8e]/10 font-semibold text-[#063e8e]'
: 'text-gray-700 hover:bg-[#063e8e]/6 hover:text-[#063e8e]',
)}
>
{child.name}
</Link>
);
})}
</div>
) : null}
</div>
);
}
const active = item.href ? isItemActive(item.href) : false;
return (
<Link
key={item.name}
href={item.href || '#'}
title={!isOpen ? item.name : undefined}
className={cn(
'group flex items-center rounded-2xl px-3 py-3 text-sm font-medium transition-all duration-200',
active
? 'bg-[#063e8e] text-white shadow-[0_12px_24px_rgba(6,62,142,0.16)]'
: 'text-gray-700 hover:bg-[#063e8e]/8 hover:text-[#063e8e]',
!isOpen && 'justify-center px-0',
)}
>
<item.icon className="h-5 w-5 shrink-0" />
{isOpen ? <span className="ml-3 truncate">{item.name}</span> : null}
</Link>
);
})}
</nav>
<div className="border-t border-[#063e8e]/12 bg-white/40 px-4 py-4 backdrop-blur-sm">
{isOpen ? (
<div className="rounded-2xl border border-[#063e8e]/10 bg-white px-4 py-3 shadow-sm">
<Link
href="/"
className="flex items-center gap-2 text-sm font-medium text-[#063e8e] hover:underline"
>
<Globe className="h-4 w-4" />
Về trang chủ
</Link>
<div className="mt-2 text-xs leading-5 text-gray-700">© 2026 VCCI HCM</div>
</div>
) : (
<Link
href="/"
title="Về trang chủ"
className="flex justify-center rounded-2xl border border-[#063e8e]/10 bg-white py-3 text-[#063e8e] shadow-sm"
>
<Globe className="h-4 w-4" />
</Link>
)}
</div>
</div>
</aside>
);
}
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
interface SidebarState {
isOpen: boolean;
toggle: () => void;
open: () => void;
close: () => void;
}
export const useSidebarStore = create<SidebarState>()(
persist(
(set) => ({
isOpen: true,
toggle: () => set((state) => ({ isOpen: !state.isOpen })),
open: () => set({ isOpen: true }),
close: () => set({ isOpen: false }),
}),
{ name: 'admin-sidebar-storage' },
),
);
"use client";
import { toSlug } from "@/mockdata/header-config";
export interface HeaderCategoryPostItem {
id: string;
category_id: string;
title: string;
slug: string;
excerpt: string;
content: string;
thumbnail: string;
published_at: string;
is_active: boolean;
created_at: string;
updated_at: string;
}
export const HEADER_CATEGORY_POSTS_STORAGE_KEY =
"vcci-news.header-category-posts.data.v1";
export const headerCategoryPostSeed: HeaderCategoryPostItem[] = [
{
id: "header-post-intro-about",
category_id: "intro-about",
title: "VCCI News và định hướng phát triển nội dung số",
slug: "vcci-news-va-dinh-huong-phat-trien-noi-dung-so",
excerpt:
"Tổng quan về định hướng vận hành, tổ chức chuyên mục và kế hoạch phát triển nội dung của VCCI News.",
content:
"<p>VCCI News tập trung phát triển hệ sinh thái nội dung gắn với hoạt động hội viên, doanh nghiệp và chuyển đổi số.</p><p>Trang này giúp đội ngũ quản trị cấu hình nhanh các điểm chạm chính trên website.</p>",
thumbnail:
"https://images.unsplash.com/photo-1497366754035-f200968a6e72?auto=format&fit=crop&w=1200&q=80",
published_at: "2026-05-01",
is_active: true,
created_at: "2026-05-01T09:00:00.000Z",
updated_at: "2026-05-01T09:00:00.000Z",
},
{
id: "header-post-activity-news-01",
category_id: "activity-news",
title: "VCCI tổ chức hội thảo kết nối doanh nghiệp khu vực phía Nam",
slug: "vcci-to-chuc-hoi-thao-ket-noi-doanh-nghiep-khu-vuc-phia-nam",
excerpt:
"Sự kiện tập trung vào giải pháp mở rộng thị trường và tăng năng lực kết nối cho doanh nghiệp hội viên.",
content:
"<p>Hội thảo quy tụ nhiều doanh nghiệp tại TP.HCM và các tỉnh lân cận nhằm chia sẻ kinh nghiệm chuyển đổi số, mở rộng xuất khẩu và nâng cao năng lực quản trị.</p>",
thumbnail:
"https://images.unsplash.com/photo-1511578314322-379afb476865?auto=format&fit=crop&w=1200&q=80",
published_at: "2026-05-07",
is_active: true,
created_at: "2026-05-07T08:15:00.000Z",
updated_at: "2026-05-07T08:15:00.000Z",
},
{
id: "header-post-activity-news-02",
category_id: "activity-news",
title: "Bản tin tuần: xu hướng đầu tư xanh trong cộng đồng doanh nghiệp",
slug: "ban-tin-tuan-xu-huong-dau-tu-xanh-trong-cong-dong-doanh-nghiep",
excerpt:
"Điểm lại các chuyển động đáng chú ý liên quan đến ESG, đầu tư xanh và năng lực cạnh tranh bền vững.",
content:
"<p>Bản tin tuần tổng hợp các chính sách mới, tín hiệu thị trường và hoạt động hỗ trợ doanh nghiệp hướng đến tăng trưởng xanh.</p>",
thumbnail:
"https://images.unsplash.com/photo-1497366412874-3415097a27e7?auto=format&fit=crop&w=1200&q=80",
published_at: "2026-05-09",
is_active: true,
created_at: "2026-05-09T03:20:00.000Z",
updated_at: "2026-05-09T03:20:00.000Z",
},
{
id: "header-post-activity-events-01",
category_id: "activity-events",
title: "Lịch sự kiện xúc tiến thương mại tháng 5",
slug: "lich-su-kien-xuc-tien-thuong-mai-thang-5",
excerpt:
"Danh sách sự kiện nổi bật dành cho hội viên trong tháng 5 với thông tin thời gian và nội dung chính.",
content:
"<p>Chuỗi sự kiện tháng 5 tập trung vào xúc tiến thương mại, kết nối đối tác và đào tạo năng lực điều hành cho doanh nghiệp hội viên.</p>",
thumbnail:
"https://images.unsplash.com/photo-1505373877841-8d25f7d46678?auto=format&fit=crop&w=1200&q=80",
published_at: "2026-05-05",
is_active: false,
created_at: "2026-05-05T10:30:00.000Z",
updated_at: "2026-05-05T10:30:00.000Z",
},
{
id: "header-post-library-highlight-01",
category_id: "library-highlight",
title: "Album ảnh hoạt động tiêu biểu quý II",
slug: "album-anh-hoat-dong-tieu-bieu-quy-ii",
excerpt:
"Tổng hợp những hình ảnh nổi bật từ các chương trình, hội thảo và sự kiện kết nối doanh nghiệp.",
content:
"<p>Album giới thiệu các hình ảnh tiêu biểu từ chuỗi hoạt động gần đây của VCCI News và hệ sinh thái hội viên.</p>",
thumbnail:
"https://images.unsplash.com/photo-1517457373958-b7bdd4587205?auto=format&fit=crop&w=1200&q=80",
published_at: "2026-05-03",
is_active: true,
created_at: "2026-05-03T06:45:00.000Z",
updated_at: "2026-05-03T06:45:00.000Z",
},
];
export interface HeaderCategoryPostFormValues {
id?: string;
title: string;
slug: string;
excerpt: string;
content: string;
thumbnail: string;
published_at: string;
is_active: boolean;
}
export const EMPTY_HEADER_CATEGORY_POST_FORM: HeaderCategoryPostFormValues = {
title: "",
slug: "",
excerpt: "",
content: "",
thumbnail: "",
published_at: "",
is_active: true,
};
export function normalizeHeaderCategoryPosts(items: HeaderCategoryPostItem[]) {
return [...items].sort((left, right) => {
const leftTime = new Date(left.published_at || left.updated_at).getTime();
const rightTime = new Date(right.published_at || right.updated_at).getTime();
return rightTime - leftTime || right.updated_at.localeCompare(left.updated_at);
});
}
export function createHeaderCategoryPostId() {
return `header-post-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
}
export function makeHeaderCategoryPostSlug(title: string) {
return toSlug(title);
}
export function getHeaderCategoryPostSeed() {
return normalizeHeaderCategoryPosts(headerCategoryPostSeed);
}
"use client";
export type HeaderCategoryType = "category" | "page" | "news" | "image";
export interface HeaderCategoryItem {
id: string;
name: string;
slug: string;
static_link: string;
sort_order: number;
type: HeaderCategoryType;
is_article: boolean;
parent_id: string | null;
level: number;
category_ids: string[];
description?: string;
created_at?: string;
updated_at?: string;
}
export interface HeaderCategoryTreeItem extends HeaderCategoryItem {
children: HeaderCategoryTreeItem[];
}
export interface HeaderArticleCategoryOption {
id: string;
name: string;
}
export const HEADER_CONFIG_STORAGE_KEY = "vcci-news.header-config.data.v1";
export const headerCategorySeed: HeaderCategoryItem[] = [
{
id: "root-home",
name: "Trang chủ",
slug: "",
static_link: "/",
sort_order: 1,
type: "page",
is_article: false,
parent_id: null,
level: 1,
category_ids: [],
description: "Trang gốc của website",
},
{
id: "intro",
name: "Giới thiệu",
slug: "gioi-thieu",
static_link: "/gioi-thieu",
sort_order: 2,
type: "category",
is_article: false,
parent_id: null,
level: 1,
category_ids: [],
description: "Nhóm nội dung giới thiệu",
},
{
id: "intro-about",
name: "Về VCCI News",
slug: "ve-vcci-news",
static_link: "/gioi-thieu/ve-vcci-news",
sort_order: 1,
type: "page",
is_article: false,
parent_id: "intro",
level: 2,
category_ids: [],
description: "Trang nội dung giới thiệu hệ thống",
},
{
id: "intro-org",
name: "Cơ cấu tổ chức",
slug: "co-cau-to-chuc",
static_link: "/gioi-thieu/co-cau-to-chuc",
sort_order: 2,
type: "page",
is_article: false,
parent_id: "intro",
level: 2,
category_ids: [],
description: "Trang thông tin cơ cấu tổ chức",
},
{
id: "activity",
name: "Hoạt động",
slug: "hoat-dong",
static_link: "/hoat-dong",
sort_order: 3,
type: "category",
is_article: false,
parent_id: null,
level: 1,
category_ids: [],
description: "Nhóm nội dung tin tức và hoạt động",
},
{
id: "activity-news",
name: "Tin tức",
slug: "tin-tuc",
static_link: "/hoat-dong/tin-tuc",
sort_order: 1,
type: "news",
is_article: true,
parent_id: "activity",
level: 2,
category_ids: ["cat-news", "cat-activity"],
description: "Danh mục tin tức tổng hợp",
},
{
id: "activity-events",
name: "Sự kiện",
slug: "su-kien",
static_link: "/hoat-dong/su-kien",
sort_order: 2,
type: "news",
is_article: true,
parent_id: "activity",
level: 2,
category_ids: ["cat-event"],
description: "Danh mục sự kiện",
},
{
id: "library",
name: "Thư viện ảnh",
slug: "thu-vien-anh",
static_link: "/thu-vien-anh",
sort_order: 4,
type: "category",
is_article: false,
parent_id: null,
level: 1,
category_ids: [],
description: "Khu vực ảnh và album",
},
{
id: "library-highlight",
name: "Album nổi bật",
slug: "album-noi-bat",
static_link: "/thu-vien-anh/album-noi-bat",
sort_order: 1,
type: "image",
is_article: false,
parent_id: "library",
level: 2,
category_ids: [],
description: "Album ảnh nổi bật",
},
];
export const headerArticleCategoryOptions: HeaderArticleCategoryOption[] = [
{ id: "cat-news", name: "Tin tổng hợp" },
{ id: "cat-activity", name: "Hoạt động VCCI" },
{ id: "cat-event", name: "Sự kiện" },
{ id: "cat-policy", name: "Chính sách" },
{ id: "cat-gallery", name: "Ảnh nổi bật" },
];
export function toSlug(value: string) {
return value
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/đ/g, "d")
.replace(/Đ/g, "D")
.toLowerCase()
.trim()
.replace(/[^a-z0-9\s-]/g, "")
.replace(/\s+/g, "-")
.replace(/-+/g, "-");
}
function buildStaticLink(
item: Pick<HeaderCategoryItem, "slug" | "parent_id">,
items: HeaderCategoryItem[],
) {
if (!item.slug.trim()) return "/";
const segments = [item.slug.trim()];
let currentParentId = item.parent_id;
while (currentParentId) {
const parent = items.find((entry) => entry.id === currentParentId);
if (!parent) break;
if (parent.slug.trim()) {
segments.unshift(parent.slug.trim());
}
currentParentId = parent.parent_id;
}
return `/${segments.join("/")}`;
}
function assignLevel(item: HeaderCategoryItem, items: HeaderCategoryItem[]) {
let level = 1;
let currentParentId = item.parent_id;
while (currentParentId) {
const parent = items.find((entry) => entry.id === currentParentId);
if (!parent) break;
level += 1;
currentParentId = parent.parent_id;
}
return level;
}
export function normalizeHeaderCategories(items: HeaderCategoryItem[]) {
const parentIds = new Set(
items.filter((item) => item.parent_id).map((item) => item.parent_id as string),
);
return items.map((item) => {
const next = { ...item };
if (parentIds.has(next.id)) {
next.type = "category";
next.category_ids = [];
}
next.level = assignLevel(next, items);
next.static_link = next.slug === "" && !next.parent_id ? "/" : buildStaticLink(next, items);
next.is_article = next.type === "news";
if (next.type !== "news") {
next.category_ids = [];
}
return next;
});
}
export function buildHeaderCategoryTree(items: HeaderCategoryItem[]): HeaderCategoryTreeItem[] {
const normalized = normalizeHeaderCategories(items);
const map = new Map<string, HeaderCategoryTreeItem>();
normalized.forEach((item) => {
map.set(item.id, { ...item, children: [] });
});
const roots: HeaderCategoryTreeItem[] = [];
normalized.forEach((item) => {
const current = map.get(item.id);
if (!current) return;
if (item.parent_id) {
const parent = map.get(item.parent_id);
if (parent) {
parent.children.push(current);
parent.children.sort(
(a, b) => a.sort_order - b.sort_order || a.name.localeCompare(b.name, "vi"),
);
} else {
roots.push(current);
}
} else {
roots.push(current);
}
});
return roots.sort(
(a, b) => a.sort_order - b.sort_order || a.name.localeCompare(b.name, "vi"),
);
}
export function getHeaderCategoryTypeLabel(type: HeaderCategoryType) {
switch (type) {
case "category":
return "Danh mục";
case "page":
return "Bài viết trang";
case "news":
return "Tin tức";
case "image":
return "Ảnh";
default:
return type;
}
}
export function createHeaderCategoryId() {
return `menu-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
}
export function getHeaderCategorySeed() {
return normalizeHeaderCategories(headerCategorySeed);
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment