Skip to content
Skills Library
Programming · Building & coding

frontend-patterns

/frontend-patterns

Framework-agnostic React/Vue patterns — component composition, hooks, TanStack Query, memoization, error boundaries. Use for generic React/Vue work (Vite, CRA, Storybook). For Next.js App Router / Server Components specifically, use `senior-frontend` instead.

Licence
MIT
Last repository change
15.05.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 15.05.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Framework-agnostic React/Vue patterns — component composition, hooks, TanStack Query, memoization, error boundaries. Use for generic React/Vue work (Vite, CRA, Storybook). For Next.js App Router / Server Components specifically, use `senior-frontend` instead.

Original author description

Framework-agnostic React/Vue patterns — component composition, hooks, TanStack Query, memoization, error boundaries. Use for generic React/Vue work (Vite, CRA, Storybook). For Next.js App Router / Server Components specifically, use `senior-frontend` instead.

How it works

  1. Critical rules (non-obvious)
  2. Component composition patterns
  3. State management decision
  4. Data fetching with TanStack Query
  5. Performance: avoid re-renders
  6. Code splitting
  7. Custom hooks pattern
  8. Error boundaries
  9. Common pitfalls
Original SKILL.md headings · 145 lines, 660 words
SKILL.md preview
---
name: frontend-patterns
type: reference
description: "Framework-agnostic React/Vue patterns — component composition, hooks, TanStack Query, memoization, error boundaries. Use for generic React/Vue work (Vite, CRA, Storybook). For Next.js App Router / Server Components specifically, use `senior-frontend` instead."
paths: ["**/*.tsx", "**/*.jsx", "**/*.vue", "**/components/**"]
effort: 3
allowed-tools: Read, Glob, Grep, Write, Edit, Bash
user-invocable: true
when_to_use: "When building React/Vue components, hooks, state management, or client-side performance — NOT for Next.js App Router (see `senior-frontend`)"
---

# Frontend Patterns

## Critical rules (non-obvious)

- **Stale closure in `useEffect`**: always list all dependencies; use `useRef` for values that shouldn't trigger re-run
- **`useEffect` with `async`**: never make the callback `async` directly — create inner async fn and call it
- **Object/array as dependency**: memoize with `useMemo`/`useCallback` or use primitive values; otherwise infinite loop
- **Key prop on lists**: use stable IDs, never `index` when list can reorder or items get deleted
- **`React.memo` is not free**: only wrap components with expensive renders and stable prop references

## Component composition patterns

```tsx
// Compound component with Context
const TabsContext = createContext<{ active: string; setActive: (v: string) => void } | null>(null);

function Tabs({ children, defaultValue }: { children: React.ReactNode; defaultValue: string }) {
  const [active, setActive] = useState(defaultValue);
  return <TabsContext.Provider value={{ active, setActive }}>{children}</TabsContext.Provider>;
}
Tabs.Trigger = function TabsTrigger({ value, children }: { value: string; children: React.ReactNode }) {
  const ctx = useContext(TabsContext)!;
  return <button onClick={() => ctx.setActive(value)} aria-selected={ctx.active === value}>{children}</button>;
};
Tabs.Content = function TabsContent({ value, children }: { value: string; children: React.ReactNode }) {
  const { active } = useContext(TabsContext)!;
  return active === value ? <>{children}</> : null;
};
```

## State management decision

| Scope | Solution |
|---|---|
| Single component | `useState`, `useReducer` |
| Subtree | Context + `useContext` |
| Client global (UI) | Zustand / Jotai |
| Server state (API) | TanStack Query |
| Form state | React Hook Form |
| URL state | `useSearchParams` (Next.js) |

## Data fetching with TanStack Query

```tsx
// Fetch
const { data, isLoading, error } = useQuery({
  queryKey: ["products", filters],   // filters in key → auto-refetch on change
  queryFn: () => api.getProducts(filters),
  staleTime: 5 * 60 * 1000,          // don't refetch for 5 min
});

// Mutate with optimistic update
const mutation = useMutation({
  mutationFn: api.updateProduct,
  onMutate: async (newProduct) => {
    await queryClient.cancelQueries({ queryKey: ["products"] });
    const prev = queryClient.getQueryData(["products"]);
    queryClient.setQueryData(["products"], (old) => old.map(p => p.id === newProduct.id ? newProduct : p));
    return { prev };
  },
  onError: (_, __, ctx) => queryClient.setQueryData(["products"], ctx?.prev),
  onSettled: () => queryClient.invalidateQueries({ queryKey: ["products"] }),
});
```

## Performance: avoid re-renders

```tsx
// Memoize expensive component
const ExpensiveList = memo(({ items }: { items: Item[] }) => (
  <ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul>
));

// Stable callback reference
const handleClick = useCallback((id: string) => {
  onSelect(id);
}, [onSelect]);  // only recreate if onSelect changes

// Expensive calculation
const sorted = useMemo(() =>
  items.sort((a, b) => b.score - a.score),
[items]);
```

## Code splitting

```tsx
const HeavyChart = lazy(() => import("./HeavyChart"));

function Dashboard() {
  return (
    <Suspense fallback={<Skeleton />}>
      <HeavyChart data={data} />
    </Suspense>
  );
}
```

## Custom hooks pattern

```tsx
function useDebounce<T>(value: T, delay: number): T {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const timer = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(timer);
  }, [value, delay]);
  return debounced;
}

function useLocalStorage<T>(key: string, initial: T) {
  const [value, setValue] = useState<T>(() => {
    try { return JSON.parse(localStorage.getItem(key) ?? "") ?? initial; }
    catch { return initial; }
  });
  const set = useCallback((v: T) => {
    setValue(v); localStorage.setItem(key, JSON.stringify(v));
  }, [key]);
  return [value, set] as const;
}
```

## Error boundaries

```tsx
class ErrorBoundary extends React.Component<{ fallback: React.ReactNode; children: React.ReactNode }> {
  state = { hasError: false };
  static getDerivedStateFromError() { return { hasError: true }; }
  componentDidCatch(error: Error) { console.error(error); }
  render() { return this.state.hasError ? this.props.fallback : this.props.children; }
}
// Usage: wrap async/complex sections, not entire app
```

## Common pitfalls

| Pitfall | Fix |
|---|---|
| Fetching in `useEffect` without cleanup | Use TanStack Query or abort controller |
| Context causes full tree re-render | Split context by domain; memoize value object |
| `useEffect` runs twice (StrictMode) | Design effects to be idempotent; use cleanup fn |
| Prop drilling > 3 levels | Lift to Context or state manager |
| Missing `loading` / `error` states | Always handle all 3 states: loading, error, data |

Versions

RepositoryScoreLicence
This page · tranhieutt/software_development_department100MIT
Sanit-mann/The-Insectoids100MIT
rommapp/romm100AGPL-3.0
tadokoro-ryusuke/cc-plugins100MIT
pekral/cursor-rules100MIT
bybren-llc/safe-agentic-workflow100MIT
bybren-llc/safe-agentic-workflow100MIT
affaan-m/ECC95MIT
affaan-m/ECC95MIT

Database snapshot: 13.11.2026 · package version 549c0daae1ac (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100tanstack-vue-query-skilld
    Hooks for managing, caching and syncing asynchronous and remote data in Vue. ALWAYS use when writing code importing \"@tanstack/vue-query\". Consult for debugging, best practices, or modifying @tanstack/vue-query, tanstack/vue-query, tanstack vue-query, tanstack vue query, query.
  • 100react-ts-vite
    React + TypeScript + Vite frontend development. Use whenever building, scaffolding, extending or refactoring a React app in TypeScript: "create a React component", "build a page with React", "add a feature to my React app", "scaffold a new Vite project", "write a custom hook",…
  • 95vue-composition
    Vue 3 with Composition API. Covers reactivity, composables, lifecycle hooks, and component patterns. USE WHEN: user mentions "Vue", "Composition API", "composables", "ref", "reactive", "v-model", "v-if", "v-for", asks about "Vue 3 patterns", "reactive state in Vue" DO NOT USE…
  • 91frontend-development
    Multi-framework frontend development:React 18+ (Suspense/hooks/TanStack), Vue 3 (Composition API), Svelte 5 (Runes), Angular (Signals). Use for components/pages, TypeScript, state management, routing, data fetching, performance. Keywords:React, Vue, Svelte, Angular, component, hooks.
  • 100trove-react
    React 19 coding conventions and performance patterns. Auto-activates when working with React/TypeScript files. Covers hooks, state management, TanStack Query, Zustand, immutable updates, and component conventions. Use when: react component; react hooks; tanstack query; zustand state.
  • 100react-frontend
    React, TypeScript, and Next.js patterns for frontend development. Use when building React components, managing state, fetching data, optimizing performance, or working with Next.js App Router. Covers React 18-19, hooks, Server Components, and type-safe patterns.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.