accelint-react-best-practices
React performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
- License 许可
- Apache-2.0
- 最近更新
- 2026-09-09
- Stars
- ★ 1
- Forks
- 0
01 前言 Front Matter
- name
- accelint-react-best-practices
- license
- Apache-2.0
- metadata
- { "author": "accelint", "version": "1.8.0" }
- description
- React performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
02 资源文件 43
- 参考文档AGENTS.md10.1 KB
- 资产文件assets/output-report-template.md9.7 KB
- 参考文档CHANGELOG.md7.2 KB
- 参考文档evals/assertions.md3.0 KB
- 参考文档evals/evals.json12.2 KB
- 参考文档README.md6.2 KB
- 参考文档references/activity-component-show-hide.md760 B
- 参考文档references/animate-svg-wrapper.md1.3 KB
- 参考文档references/avoid-usememo-simple-expressions.md1.2 KB
- 参考文档references/cache-repeated-function-calls.md2.0 KB
- 参考文档references/calculate-derived-state.md1.3 KB
- 参考文档references/compound-patterns.md21.6 KB
- 参考文档references/css-content-visibility.md954 B
- 参考文档references/defer-state-reads.md1.1 KB
- 参考文档references/effect-event-deps.md1.9 KB
- 参考文档references/extract-default-parameter-value.md1.3 KB
- 参考文档references/extract-memoized-components.md1.1 KB
- 参考文档references/functional-setstate-updates.md2.1 KB
- 参考文档references/hoist-regexp-creation.md1.2 KB
- 参考文档references/hoist-static-jsx.md995 B
- 参考文档references/initialize-app-once.md1.1 KB
- 参考文档references/interaction-logic-in-event-handlers.md1.4 KB
- 参考文档references/lazy-state-initialization.md2.1 KB
- 参考文档references/named-imports.md716 B
- 参考文档references/narrow-effect-dependencies.md1.0 KB
- 参考文档references/no-forwardref.md696 B
- 参考文档references/no-inline-components.md1.9 KB
- 参考文档references/optimize-svg-precision.md836 B
- 参考文档references/prevent-hydration-mismatch.md2.8 KB
- 参考文档references/quick-checklists.md9.3 KB
- 参考文档references/react-compiler-guide.md6.4 KB
- 参考文档references/split-combined-hooks.md1.6 KB
- 参考文档references/store-event-handlers-refs.md1.3 KB
- 参考文档references/subscribe-derived-state.md953 B
- 参考文档references/transitions-non-urgent-updates.md1.2 KB
- 参考文档references/use-deferred-value.md1.6 KB
- 参考文档references/use-usetransition-over-manual-loading.md2.1 KB
- 参考文档references/uselatest-stable-callbacks.md2.4 KB
- 参考文档references/useref-for-transient-values.md1.9 KB
- 脚本scripts/check-imports.sh1.5 KB
- 脚本scripts/detect-static-jsx.sh2.9 KB
- 脚本scripts/find-forwardref.sh1.6 KB
- 脚本scripts/README.md4.5 KB
03 SKILL.md 正文
React Best Practices
Comprehensive performance optimization and best practices for React applications, designed for AI agents and LLMs working with React code.
NEVER Do React
These are the most critical anti-patterns that cause real production issues. Experts learned these the hard way through debugging sessions and performance investigations.
NEVER define components inside components — creates new component type on every render, causing full remount with state loss and DOM recreation. Results in input fields losing focus on keystroke, animations restarting unexpectedly, and useEffect cleanup/setup running on every parent render.
NEVER subscribe to searchParams/localStorage if you only read them in callbacks — causes component to re-render on every URL change or storage event even when the component doesn't display those values. Read directly in the callback instead: new URLSearchParams(window.location.search).
NEVER use object/array dependencies in useEffect — triggers effect on every render since objects are recreated with new references each time. Extract primitive values (id, name) from objects and use those as dependencies instead.
NEVER sync derived state with useState + useEffect — leads to extra re-renders, infinite loops, and stale intermediate states. Calculate derived values during render instead: const fullName = firstName + ' ' + lastName.
NEVER use client-only state (localStorage, cookies, device detection) directly in SSR components — causes hydration mismatches where server HTML doesn't match client render, resulting in React warnings, visual flickering, and broken interactivity. Use synchronous inline <script> before React hydrates.
NEVER use forwardRef in React 19+ — deprecated API. Use ref as a regular prop instead: function MyInput({ ref }) { return <input ref={ref} /> }.
NEVER create callbacks/objects/arrays inline as props to memoized components — breaks memoization since new reference is created each render. Extract to module scope, useMemo, or useCallback: const config = useMemo(() => ({ theme }), [theme]).
NEVER put user interaction logic in useEffect — if it's triggered by a button click or form submit, put it directly in the event handler. Effects are for synchronization with external systems, not user-triggered actions.
Before Optimizing Performance, Ask
Before suggesting memo/useMemo/useCallback optimizations, determine if they're needed:
-
Does this project use React Compiler?
- Search for
babel-plugin-react-compilerorreact-compiler-webpack-pluginin package.json/config files - If yes → Skip manual memoization (memo, useMemo, useCallback, hoisting static JSX) — the compiler handles these automatically
- If no → Apply all relevant optimizations from this skill
- See react-compiler-guide.md for what the compiler handles
- Search for
-
Is this actually a performance problem?
- Has the user measured/profiled and identified a bottleneck?
- Or are they asking for a general review/optimization?
-
What's the scale?
- For lists: How many items? (affects whether to suggest content-visibility vs virtualization)
- For re-renders: How often does this component re-render?
How to Use
This skill uses a progressive disclosure structure to minimize context usage:
1. Start with the Overview (AGENTS.md)
Read AGENTS.md for a concise overview of all rules with one-line summaries.
2. Load Specific Rules as Needed
When you identify a relevant optimization, load the corresponding reference file for detailed implementation guidance:
Re-render Optimizations:
- defer-state-reads.md
- extract-memoized-components.md
- narrow-effect-dependencies.md
- subscribe-derived-state.md
- functional-setstate-updates.md
- lazy-state-initialization.md
- transitions-non-urgent-updates.md
- calculate-derived-state.md
- avoid-usememo-simple-expressions.md
- extract-default-parameter-value.md
- interaction-logic-in-event-handlers.md
- no-inline-components.md
- useref-for-transient-values.md
- split-combined-hooks.md
- use-deferred-value.md
Rendering Performance:
- animate-svg-wrapper.md
- css-content-visibility.md
- hoist-static-jsx.md
- optimize-svg-precision.md
- prevent-hydration-mismatch.md
- activity-component-show-hide.md
- hoist-regexp-creation.md
- use-usetransition-over-manual-loading.md
Advanced Patterns:
- store-event-handlers-refs.md
- uselatest-stable-callbacks.md
- cache-repeated-function-calls.md
- initialize-app-once.md
- effect-event-deps.md
Misc:
Quick References:
Automation Scripts:
- scripts/ - Helper scripts to detect anti-patterns
3. Apply the Pattern
Each reference file contains:
- ❌ Incorrect examples showing the anti-pattern
- ✅ Correct examples showing the optimal implementation
- Explanations of why the pattern matters
4. Use the Report Template
When this skill is invoked, use the standardized report format:
Template: assets/output-report-template.md
The report format provides:
- Executive Summary with impact assessment
- Severity levels (Critical, High, Medium, Low) for prioritization
- Impact analysis (potential bugs, type safety, maintainability, runtime failures)
- Categorization (Type Safety, Safety, State Management, Return Values, Code Quality)
- Pattern references linking to detailed guidance in references/
- Phase 2 summary table for tracking all issues
When to use the audit template:
- Skill invoked directly via
/accelint-react-best-practices <path> - User asks to "review code quality" or "audit code" across file(s), invoking skill implicitly
When NOT to use the report template:
- User asks to "fix this type error" (direct implementation)
- User asks "what's wrong with this code?" (answer the question)
- User requests specific fixes (apply fixes directly without formal report)
Examples
Example 1: Optimizing Re-renders
Task: "This component re-renders too frequently when the user scrolls"
Approach:
- Read AGENTS.md overview
- Identify likely cause: subscribing to continuous values (scroll position)
- Load subscribe-derived-state.md or transitions-non-urgent-updates.md
- Apply the pattern from the reference file
Example 2: Fixing Stale Closures
Task: "This callback always uses the old state value"
Approach:
- Read AGENTS.md overview
- Identify issue: stale closure in useCallback
- Load functional-setstate-updates.md
- Replace direct state reference with functional update
Example 3: SSR Hydration Mismatch
Task: "Getting hydration errors with localStorage theme"
Approach:
- Read AGENTS.md overview
- Identify issue: client-only state causing mismatch
- Load prevent-hydration-mismatch.md
- Implement synchronous script pattern
Using Skill Patterns Appropriately
Each reference file demonstrates ONE proven pattern, but React problems often have multiple valid solutions.
When applying patterns:
- ✅ Present the pattern from the reference file
- ✅ Mention alternative approaches when they exist
- ✅ Consider user's React version, project complexity, and team preferences
- ✅ For simple cases, suggest simpler solutions even if not in references
Example: For SSR hydration issues, prevent-hydration-mismatch.md shows the synchronous script approach, but a simple "mounted flag" pattern may be more appropriate for basic use cases.
Important Notes
React Compiler Awareness
Many manual optimization patterns (memo, useMemo, useCallback, hoisting static JSX) are automatically handled by React Compiler.
Before optimizing, check if the project uses React Compiler:
- If enabled: Skip manual memoization, but still apply state/effect/CSS optimizations
- If not enabled: Apply all relevant optimizations from this guide
See react-compiler-guide.md for a complete breakdown of what the compiler handles vs what still needs manual optimization.
React 19+ Features
This skill covers React 19 features including:
useEffectEvent(19.2+) for stable event handlers<Activity>component for preserving hidden component staterefas a prop (replaces deprecatedforwardRef)- Named imports only (no default import of React)
Performance Philosophy
- Start with correct code, then optimize
- Measure before optimizing
- Optimize slowest operations first (network > rendering > computation)
- Avoid premature optimization of trivial operations
Code Quality Principles
- Prefer simple, readable code over clever optimizations
- Only add complexity when measurements justify it
- Document non-obvious performance optimizations
Additional Resources
Catch up on React 19 features:
04 同仓库更多 Skills
zustand-state-management
Production-tested setup for Zustand state management in React applications with TypeScript. This skill provides comprehensive patterns for building scalable, type-safe global state. Use when: setting up global state in React, migrating from Redux or Context API, implementing state persistence with localStorage, configuring TypeScript with Zustand, using slices pattern for modular stores, adding devtools middleware for debugging, handling Next.js SSR hydration, or encountering hydration errors, TypeScript inference issues, or persist middleware problems. Prevents 5 documented issues: Next.js hydration mismatches, TypeScript double parentheses syntax errors, persist middleware export errors, infinite render loops, and slices pattern type inference failures. Keywords: zustand, state management, React state, TypeScript state, persist middleware, devtools, slices pattern, global state, React hooks, create store, useBoundStore, StateCreator, hydration error, text content mismatch, infinite render, localStorage, sessionStorage, immer middleware, shallow equality, selector pattern, zustand v5
zetic-mlange
Help users integrate the ZETIC Melange (MLange) on-device AI SDK into Android (Kotlin/Java) and iOS (Swift) mobile apps. Use this skill whenever the user mentions Zetic, MLange, Melange, ZeticMLangeModel, ZeticMLangeLLMModel, ZeticMLangeHFModel, on-device NPU inference for mobile, or deploying ML models to Android/iOS with NPU acceleration. Also trigger when users ask about running LLMs on-device with GGUF quantization, mobile NPU model deployment, or converting PyTorch/ONNX models for mobile inference. Covers general model inference, LLM inference (streaming token generation), and HuggingFace model loading.
youtube-downloader
Download videos, audio, playlists, and channels from YouTube and 1000+ websites using yt-dlp. Supports quality selection, format conversion, subtitle download, playlist filtering, metadata extraction, thumbnail download, and batch operations. Use when downloading YouTube videos in any quality (4K, 8K, HDR), extracting audio as MP3/M4A/FLAC, downloading entire playlists/channels, getting subtitles in multiple languages, converting to specific formats, downloading live streams, archiving content, or batch processing multiple URLs. Optimized for reliability with automatic retries, rate limiting, and error handling.
wordpress-plugin-core
This skill provides comprehensive knowledge for WordPress plugin development, covering core patterns, security best practices, database interactions, hooks/filters, Settings API, custom post types, REST API, and AJAX. This skill should be used when creating WordPress plugins, troubleshooting security issues, implementing custom post types/taxonomies, building admin interfaces, or working with the WordPress database. Use when: Creating new WordPress plugins, implementing nonces/sanitization/escaping, working with $wpdb and prepared statements, building Settings API pages, registering custom post types or taxonomies, implementing REST API endpoints, handling AJAX requests, debugging plugin activation/deactivation issues, preventing SQL injection/XSS/CSRF vulnerabilities. Keywords: wordpress plugin development, wordpress security, wordpress hooks, wordpress filters, wordpress database, wpdb prepare, sanitize_text_field, esc_html, wp_nonce, custom post type, register_post_type, settings api, rest api, admin-ajax, wordpress sql injection, wordpress xss, wordpress csrf, plugin header, activation hook, deactivation hook, wordpress coding standards, wordpress plugin architecture
webapp-testing
Test local web applications with Playwright. Use when asked to verify frontend functionality, debug UI behavior, capture browser screenshots, or inspect browser logs.
web-performance-audit
Audit web performance using Chrome DevTools MCP. Use when asked to audit, profile, debug, or optimize page load performance, Lighthouse scores, or site speed.