react-patterns
БесплатноБез исполняемых скриптовНе проверенReact component patterns and architectural best practices. Covers compound components, render props, higher-order components, custom hooks, composition, state…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
React Patterns
Full Reference: See advanced.md for Container/Presentational, State Machine, Slots, Polymorphic, and Provider patterns.
Compound Components
Components that work together to form a cohesive UI:
import { createContext, useContext, useState, ReactNode } from 'react';
interface AccordionContextValue {
openItems: Set<string>;
toggle: (id: string) => void;
}
const AccordionContext = createContext<AccordionContextValue | null>(null);
function useAccordion() {
const context = useContext(AccordionContext);
if (!context) {
throw new Error('Accordion components must be used within Accordion');
}
return context;
}
function Accordion({ children, multiple = false, defaultOpen = [] }: AccordionProps) {
const [openItems, setOpenItems] = useState<Set<string>>(new Set(defaultOpen));
const toggle = (id: string) => {
setOpenItems((prev) => {
const next = new Set(prev);
if (next.has(id)) {
next.delete(id);
} else {
if (!multiple) next.clear();
next.add(id);
}
return next;
});
};
return (
<AccordionContext.Provider value={{ openItems, toggle }}>
<div className="accordion">{children}</div>
</AccordionContext.Provider>
);
}
// Attach sub-components
Accordion.Item = Item;
Accordion.Trigger = Trigger;
Accordion.Content = Content;
Render Props
Pass a function as children or prop to control rendering:
interface DataFetcherProps<T> {
url: string;
children: (state: {
data: T | null;
loading: boolean;
error: Error | null;
refetch: () => void;
}) => ReactNode;
}
function DataFetcher<T>({ url, children }: DataFetcherProps<T>) {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const fetchData = useCallback(async () => {
setLoading(true);
setError(null);
try {
const res = await fetch(url);
if (!res.ok) throw new Error('Failed to fetch');
setData(await res.json());
} catch (e) {
setError(e as Error);
} finally {
setLoading(false);
}
}, [url]);
useEffect(() => { fetchData(); }, [fetchData]);
return <>{children({ data, loading, error, refetch: fetchData })}</>;
}
// Usage
<DataFetcher<User[]> url="/api/users">
{({ data, loading, error, refetch }) => {
if (loading) return <Spinner />;
if (error) return <ErrorMessage error={error} onRetry={refetch} />;
return <ul>{data?.map(user => <li key={user.id}>{user.name}</li>)}</ul>;
}}
</DataFetcher>
Higher-Order Components (HOC)
Wrap components to add functionality:
function withLoading<P extends object>(
WrappedComponent: React.ComponentType<P>,
LoadingComponent: React.ComponentType = DefaultSpinner
) {
return function WithLoadingComponent(props: P & { loading: boolean }) {
const { loading, ...restProps } = props;
if (loading) return <LoadingComponent />;
return <WrappedComponent {...(restProps as P)} />;
};
}
// HOC with Refs
function withLogger<P extends object>(WrappedComponent: React.ComponentType<P>) {
const WithLogger = React.forwardRef<unknown, P>((props, ref) => {
useEffect(() => { console.log('Props changed:', props); }, [props]);
return <WrappedComponent {...props} ref={ref} />;
});
WithLogger.displayName = `WithLogger(${WrappedComponent.displayName || WrappedComponent.name})`;
return WithLogger;
}
Custom Hooks Pattern
Extract reusable logic into hooks:
// useLocalStorage
function useLocalStorage<T>(key: string, initialValue: T) {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch { return initialValue; }
});
const setValue = useCallback((value: T | ((val: T) => T)) => {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}, [key, storedValue]);
return [storedValue, setValue] as const;
}
// useDebounce
function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}
// useOnClickOutside
function useOnClickOutside(
ref: RefObject<HTMLElement>,
handler: (event: MouseEvent | TouchEvent) => void
) {
useEffect(() => {
const listener = (event: MouseEvent | TouchEvent) => {
if (!ref.current || ref.current.contains(event.target as Node)) return;
handler(event);
};
document.addEventListener('mousedown', listener);
document.addEventListener('touchstart', listener);
return () => {
document.remo
Установить react-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditВложенные файлы
FAQ
Что делает скилл react-patterns?
React component patterns and architectural best practices. Covers compound components, render props, higher-order components, custom hooks, composition, state machines, and container/presentational patterns. USE WHEN: user mentions "compound components", "render props", "HOC", "higher-order component", "composition pattern", "component architecture", asks about "reusable components", "component patterns", "slots pattern", "polymorphic components" DO NOT USE FOR: Basic React components - use `react` skill instead, hooks implementation - use `react-hooks` skill instead, performance patterns - use `react-performance` skill instead
Как установить скилл react-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл react-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
frontend-design
Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making…
от Anthropicwebapp-testing
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing…
от Anthropicbrand-guidelines
Applies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand…
от Anthropicweb-artifacts-builder
Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use…
от Anthropic