$npx -y skills add tranhieutt/software_development_department --skill frontend-patternsFramework-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.
| 1 | # Frontend Patterns |
| 2 | |
| 3 | ## Critical rules (non-obvious) |
| 4 | |
| 5 | - **Stale closure in `useEffect`**: always list all dependencies; use `useRef` for values that shouldn't trigger re-run |
| 6 | - **`useEffect` with `async`**: never make the callback `async` directly — create inner async fn and call it |
| 7 | - **Object/array as dependency**: memoize with `useMemo`/`useCallback` or use primitive values; otherwise infinite loop |
| 8 | - **Key prop on lists**: use stable IDs, never `index` when list can reorder or items get deleted |
| 9 | - **`React.memo` is not free**: only wrap components with expensive renders and stable prop references |
| 10 | |
| 11 | ## Component composition patterns |
| 12 | |
| 13 | ```tsx |
| 14 | // Compound component with Context |
| 15 | const TabsContext = createContext<{ active: string; setActive: (v: string) => void } | null>(null); |
| 16 | |
| 17 | function Tabs({ children, defaultValue }: { children: React.ReactNode; defaultValue: string }) { |
| 18 | const [active, setActive] = useState(defaultValue); |
| 19 | return <TabsContext.Provider value={{ active, setActive }}>{children}</TabsContext.Provider>; |
| 20 | } |
| 21 | Tabs.Trigger = function TabsTrigger({ value, children }: { value: string; children: React.ReactNode }) { |
| 22 | const ctx = useContext(TabsContext)!; |
| 23 | return <button onClick={() => ctx.setActive(value)} aria-selected={ctx.active === value}>{children}</button>; |
| 24 | }; |
| 25 | Tabs.Content = function TabsContent({ value, children }: { value: string; children: React.ReactNode }) { |
| 26 | const { active } = useContext(TabsContext)!; |
| 27 | return active === value ? <>{children}</> : null; |
| 28 | }; |
| 29 | ``` |
| 30 | |
| 31 | ## State management decision |
| 32 | |
| 33 | | Scope | Solution | |
| 34 | |---|---| |
| 35 | | Single component | `useState`, `useReducer` | |
| 36 | | Subtree | Context + `useContext` | |
| 37 | | Client global (UI) | Zustand / Jotai | |
| 38 | | Server state (API) | TanStack Query | |
| 39 | | Form state | React Hook Form | |
| 40 | | URL state | `useSearchParams` (Next.js) | |
| 41 | |
| 42 | ## Data fetching with TanStack Query |
| 43 | |
| 44 | ```tsx |
| 45 | // Fetch |
| 46 | const { data, isLoading, error } = useQuery({ |
| 47 | queryKey: ["products", filters], // filters in key → auto-refetch on change |
| 48 | queryFn: () => api.getProducts(filters), |
| 49 | staleTime: 5 * 60 * 1000, // don't refetch for 5 min |
| 50 | }); |
| 51 | |
| 52 | // Mutate with optimistic update |
| 53 | const mutation = useMutation({ |
| 54 | mutationFn: api.updateProduct, |
| 55 | onMutate: async (newProduct) => { |
| 56 | await queryClient.cancelQueries({ queryKey: ["products"] }); |
| 57 | const prev = queryClient.getQueryData(["products"]); |
| 58 | queryClient.setQueryData(["products"], (old) => old.map(p => p.id === newProduct.id ? newProduct : p)); |
| 59 | return { prev }; |
| 60 | }, |
| 61 | onError: (_, __, ctx) => queryClient.setQueryData(["products"], ctx?.prev), |
| 62 | onSettled: () => queryClient.invalidateQueries({ queryKey: ["products"] }), |
| 63 | }); |
| 64 | ``` |
| 65 | |
| 66 | ## Performance: avoid re-renders |
| 67 | |
| 68 | ```tsx |
| 69 | // Memoize expensive component |
| 70 | const ExpensiveList = memo(({ items }: { items: Item[] }) => ( |
| 71 | <ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul> |
| 72 | )); |
| 73 | |
| 74 | // Stable callback reference |
| 75 | const handleClick = useCallback((id: string) => { |
| 76 | onSelect(id); |
| 77 | }, [onSelect]); // only recreate if onSelect changes |
| 78 | |
| 79 | // Expensive calculation |
| 80 | const sorted = useMemo(() => |
| 81 | items.sort((a, b) => b.score - a.score), |
| 82 | [items]); |
| 83 | ``` |
| 84 | |
| 85 | ## Code splitting |
| 86 | |
| 87 | ```tsx |
| 88 | const HeavyChart = lazy(() => import("./HeavyChart")); |
| 89 | |
| 90 | function Dashboard() { |
| 91 | return ( |
| 92 | <Suspense fallback={<Skeleton />}> |
| 93 | <HeavyChart data={data} /> |
| 94 | </Suspense> |
| 95 | ); |
| 96 | } |
| 97 | ``` |
| 98 | |
| 99 | ## Custom hooks pattern |
| 100 | |
| 101 | ```tsx |
| 102 | function useDebounce<T>(value: T, delay: number): T { |
| 103 | const [debounced, setDebounced] = useState(value); |
| 104 | useEffect(() => { |
| 105 | const timer = setTimeout(() => setDebounced(value), delay); |
| 106 | return () => clearTimeout(timer); |
| 107 | }, [value, delay]); |
| 108 | return debounced; |
| 109 | } |
| 110 | |
| 111 | function useLocalStorage<T>(key: string, initial: T) { |
| 112 | const [value, setValue] = useState<T>(() => { |
| 113 | try { return JSON.parse(localStorage.getItem(key) ?? "") ?? initial; } |
| 114 | catch { return initial; } |
| 115 | }); |
| 116 | const set = useCallback((v: T) => { |
| 117 | setValue(v); localStorage.setItem(key, JSON.stringify(v)); |
| 118 | }, [key]); |
| 119 | return [value, set] as const; |
| 120 | } |
| 121 | ``` |
| 122 | |
| 123 | ## Error boundaries |
| 124 | |
| 125 | ```tsx |
| 126 | class ErrorBoundary extends React.Component<{ fallback: React.ReactNode; children: React.ReactNode }> { |
| 127 | state = { hasError: false }; |
| 128 | static getDerivedStateFromError() { return { hasError: true }; } |
| 129 | componentDidCatch(error: Error) { console.error(error); } |
| 130 | render() { return this.state.hasError ? this.props.fallback : this.pr |