# React and Next.js Frontend Patterns Recommended by Everything Claude Code

> Discover React and Next.js frontend patterns recommended by Everything Claude Code. Learn composition, custom hooks, state management, and memoization for scalable apps.

- Repository: [Affaan Mustafa/everything-claude-code](https://github.com/affaan-m/everything-claude-code)
- Tags: patterns
- Published: 2026-03-20

---

**Everything Claude Code recommends composition-based component architecture, custom hooks for local state, Context with Reducer for global state, and strategic memoization with code splitting to build scalable React and Next.js applications.**

Everything Claude Code (ECC) defines a comprehensive set of **frontend development patterns** that guide the architecture of React components and Next.js applications. These patterns are documented in the central skill file [[`skills/frontend-patterns/SKILL.md`](https://github.com/affaan-m/everything-claude-code/blob/main/skills/frontend-patterns/SKILL.md)](https://github.com/affaan-m/everything-claude-code/blob/main/skills/frontend-patterns/SKILL.md) within the repository. The recommendations prioritize component reusability, predictable state management, and performance optimizations that keep applications responsive at scale.

## Component Composition Patterns

ECC advocates for composition over inheritance when building React UI elements. This approach produces small, self-contained components that accept `children` and optional props, allowing parents to assemble complex interfaces through JSX nesting.

### Composition Over Inheritance

The foundational pattern involves creating atomic components like `Card`, `CardHeader`, and `CardBody` that encapsulate their own styling and behavior. Each component accepts `children` to allow flexible content injection.

```tsx
// components/Card.tsx
interface CardProps {
  children: React.ReactNode
  variant?: 'default' | 'outlined'
}
export function Card({ children, variant = 'default' }: CardProps) {
  return <div className={`card card-${variant}`}>{children}</div>
}
export function CardHeader({ children }: { children: React.ReactNode }) {
  return <div className="card-header">{children}</div>
}
export function CardBody({ children }: { children: React.ReactNode }) {
  return <div className="card-body">{children}</div>
}

/* Usage */
<Card>
  <CardHeader>Title</CardHeader>
  <CardBody>Content goes here</CardBody>
</Card>

```

### Compound Components

For complex UI widgets like tabs, accordions, or dropdowns that require shared internal state, ECC recommends the Compound Components pattern. A context provider supplies state to child parts, while each part validates its usage context.

```tsx
// components/Tabs.tsx
import { createContext, useContext, useState } from 'react'

interface TabsContextValue {
  activeTab: string
  setActiveTab: (tab: string) => void
}
const TabsContext = createContext<TabsContextValue | undefined>(undefined)

export function Tabs({ children, defaultTab }: { children: React.ReactNode; defaultTab: string }) {
  const [activeTab, setActiveTab] = useState(defaultTab)
  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      {children}
    </TabsContext.Provider>
  )
}
export function TabList({ children }: { children: React.ReactNode }) {
  return <div className="tab-list">{children}</div>
}
export function Tab({ id, children }: { id: string; children: React.ReactNode }) {
  const ctx = useContext(TabsContext)
  if (!ctx) throw new Error('Tab must be used within Tabs')
  return (
    <button className={ctx.activeTab === id ? 'active' : ''} onClick={() => ctx.setActiveTab(id)}>
      {children}
    </button>
  )
}

/* Usage */
<Tabs defaultTab="overview">
  <TabList>
    <Tab id="overview">Overview</Tab>
    <Tab id="details">Details</Tab>
  </TabList>
</Tabs>

```

### Render Props Pattern

When a component must expose dynamic data handling to its consumer without dictating UI structure, ECC suggests the Render Props pattern. The child is a function receiving data, loading, and error flags, allowing the parent to control rendering logic while the component manages the data flow.

## State Management Patterns

ECC distinguishes between local UI state and shared global state, recommending different patterns for each to maintain predictability and performance.

### Custom Hooks for Local State

For component-specific logic, ECC defines reusable custom hooks that encapsulate stateful behavior. These include `useToggle` for boolean switches, `useDebounce` for rate-limiting rapid changes, and `useQuery` for async data fetching.

```tsx
// hooks/useQuery.ts
import { useState, useEffect, useCallback } from 'react'

export function useQuery<T>(key: string, fetcher: () => Promise<T>, options?: {
  onSuccess?: (data: T) => void
  onError?: (error: Error) => void
  enabled?: boolean
}) {
  const [data, setData] = useState<T | null>(null)
  const [error, setError] = useState<Error | null>(null)
  const [loading, setLoading] = useState(false)

  const refetch = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const result = await fetcher()
      setData(result)
      options?.onSuccess?.(result)
    } catch (e) {
      const err = e as Error
      setError(err)
      options?.onError?.(err)
    } finally {
      setLoading(false)
    }
  }, [fetcher, options])

  useEffect(() => {
    if (options?.enabled !== false) {
      refetch()
    }
  }, [key, refetch, options?.enabled])

  return { data, error, loading, refetch }
}

```

### Context with Reducer for Global State

For shared, mutable state across the component tree, ECC recommends the **Context + Reducer** pattern. This approach combines React's Context API for dependency injection with the Reducer pattern for predictable state updates.

The implementation involves creating a `State` interface describing the slice, defining action types, building an immutable `reducer`, and providing state and `dispatch` via a React context. A custom hook like `useMarkets` enforces provider presence.

```tsx
// context/MarketContext.tsx
import { createContext, useContext, useReducer, ReactNode } from 'react'

interface Market { id: string; name: string; volume: number }
interface State {
  markets: Market[]
  selectedMarket: Market | null
  loading: boolean
}
type Action =
  | { type: 'SET_MARKETS'; payload: Market[] }
  | { type: 'SELECT_MARKET'; payload: Market }
  | { type: 'SET_LOADING'; payload: boolean }

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'SET_MARKETS':
      return { ...state, markets: action.payload }
    case 'SELECT_MARKET':
      return { ...state, selectedMarket: action.payload }
    case 'SET_LOADING':
      return { ...state, loading: action.payload }
    default:
      return state
  }
}

const MarketContext = createContext<{ state: State; dispatch: React.Dispatch<Action> } | undefined>(undefined)

export function MarketProvider({ children }: { children: ReactNode }) {
  const [state, dispatch] = useReducer(reducer, { markets: [], selectedMarket: null, loading: false })
  return <MarketContext.Provider value={{ state, dispatch }}>{children}</MarketContext.Provider>
}
export function useMarkets() {
  const ctx = useContext(MarketContext)
  if (!ctx) throw new Error('useMarkets must be used within MarketProvider')
  return ctx
}

```

## Performance Optimization Patterns

ECC emphasizes maintaining application responsiveness through strategic memoization, code splitting, and virtualization techniques.

### Memoization Strategies

To avoid unnecessary re-renders and expensive calculations, ECC recommends wrapping expensive sorts in `useMemo`, memoizing event handlers with `useCallback`, and wrapping pure presentational components with `React.memo`.

### Code Splitting and Lazy Loading

For reducing initial bundle size, ECC suggests using `React.lazy` combined with `Suspense` to dynamically import heavy components like charts or 3D visualizations.

```tsx
import { lazy, Suspense } from 'react'

const HeavyChart = lazy(() => import('./HeavyChart'))

export function Dashboard() {
  return (
    <Suspense fallback={<div>Loading chart…</div>}>
      <HeavyChart />
    </Suspense>
  )
}

```

### List Virtualization

For efficiently rendering long lists, ECC recommends using `@tanstack/react-virtual` to calculate visible item indices and absolute positioning, rendering only the rows visible in the viewport plus a configurable overscan buffer.

```tsx
import { useVirtualizer } from '@tanstack/react-virtual'

export function VirtualMarketList({ markets }: { markets: Market[] }) {
  const parentRef = useRef<HTMLDivElement>(null)

  const virtualizer = useVirtualizer({
    count: markets.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 100,
    overscan: 5,
  })

  return (
    <div ref={parentRef} style={{ height: '600px', overflow: 'auto' }}>
      <div style={{ height: `${virtualizer.getTotalSize()}px`, position: 'relative' }}>
        {virtualizer.getVirtualItems().map(item => (
          <div
            key={item.index}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              height: `${item.size}px`,
              transform: `translateY(${item.start}px)`,
            }}
          >
            <MarketCard market={markets[item.index]} />
          </div>
        ))}
      </div>
    </div>
  )
}

```

### Animation and Accessibility

For smooth UI feedback without layout thrashing, ECC suggests using `framer-motion` to wrap list items or modals with `<motion.div>` and define `initial`, `animate`, and `exit` states. For accessibility, implement keyboard navigation patterns, trap focus in modals, and respect `prefers-reduced-motion` media queries.

## Summary

Everything Claude Code establishes a structured approach to React and Next.js development through three architectural pillars:

- **Component Composition**: Favor composition over inheritance using compound components and render props for flexible, reusable UI pieces
- **Predictable State Management**: Encapsulate local logic in custom hooks like `useQuery` and `useToggle`, while scaling global state through the Context + Reducer pattern as documented in [`skills/frontend-patterns/SKILL.md`](https://github.com/affaan-m/everything-claude-code/blob/main/skills/frontend-patterns/SKILL.md)
- **Performance-First Architecture**: Implement memoization strategies, code splitting with `React.lazy` and `Suspense`, list virtualization via `@tanstack/react-virtual`, and accessibility-compliant animations

## Frequently Asked Questions

### What is the Everything Claude Code repository?

Everything Claude Code (ECC) is an open-source knowledge base that codifies best practices for software development, including comprehensive frontend patterns for React and Next.js applications. The repository organizes these recommendations into skill files, with [`skills/frontend-patterns/SKILL.md`](https://github.com/affaan-m/everything-claude-code/blob/main/skills/frontend-patterns/SKILL.md) serving as the primary reference for component architecture and state management.

### When should I use Context with Reducer versus useState?

Use the Context with Reducer pattern when state needs to be shared across multiple component trees or when updates involve complex logic that benefits from centralized action handling. For component-local state or simple boolean toggles, prefer `useState` or custom hooks like `useToggle` to avoid unnecessary re-renders and coupling.

### How does ECC recommend handling expensive computations in React?

ECC recommends wrapping expensive calculations in `useMemo` to cache results between renders, memoizing event handlers with `useCallback` to prevent child re-renders, and wrapping pure presentational components with `React.memo`. For heavy UI components like charts, implement code splitting using `React.lazy` and `Suspense` to defer loading until needed.

### What virtualization library does Everything Claude Code recommend for long lists?

According to the [`skills/frontend-patterns/SKILL.md`](https://github.com/affaan-m/everything-claude-code/blob/main/skills/frontend-patterns/SKILL.md) file, ECC recommends using `@tanstack/react-virtual` for rendering long lists efficiently. This approach uses the `useVirtualizer` hook to calculate visible item indices and absolute positioning, rendering only the rows visible in the viewport plus a configurable overscan buffer.