### Example: Lazy Initialization with Large Arrays
Source: https://www.react.doctor/docs/rules/react-doctor/rerender-lazy-state-init
Illustrates using lazy initialization for precomputing large arrays. This prevents the array from being recreated on every render, optimizing performance for costly setup operations.
```javascript
useState(() => [...Array(10000)].map((_, i) => i))
```
--------------------------------
### Install Command Usage
Source: https://www.react.doctor/docs/reference/cli-reference
Install React Doctor, including optional local hooks and agent configurations. Use the '-y' flag to skip prompts and apply default settings.
```bash
react-doctor install [options]
```
--------------------------------
### Direct Path Import Example
Source: https://www.react.doctor/docs/rules/react-doctor/no-barrel-import
Import components directly from their source file path instead of a barrel file.
```javascript
import { Button } from './components/Button'
```
--------------------------------
### Install React Doctor for CI/CD
Source: https://www.react.doctor/docs
Run this command to install React Doctor and configure it to check every pull request using GitHub Actions.
```bash
npx react-doctor@latest install
```
--------------------------------
### Example: Dynamic Import for Monaco Editor
Source: https://www.react.doctor/docs/rules/react-doctor/prefer-dynamic-import
Replace static imports of Monaco Editor with `next/dynamic` and disable SSR.
```javascript
const Editor = dynamic(() => import("@monaco-editor/react"), { ssr: false })
```
--------------------------------
### No Store Example
Source: https://www.react.doctor/docs/rules/react-doctor/server-fetch-without-revalidate
Use `{ cache: 'no-store' }` for fully dynamic data that should not be cached.
```javascript
fetch(url, { cache: 'no-store' })
```
--------------------------------
### Barrel Import Example
Source: https://www.react.doctor/docs/rules/react-doctor/no-barrel-import
Avoid importing from barrel files like './components' which re-export multiple modules.
```javascript
import { Button } from './components'
```
--------------------------------
### Function Component Conversion
Source: https://www.react.doctor/docs/rules/react-doctor/prefer-function-component
This demonstrates the converted function component equivalent of the class component example, utilizing props directly.
```javascript
function Foo({ foo }) {
return
{foo}
;
}
```
--------------------------------
### useState with Non-Conventional Value Name
Source: https://www.react.doctor/docs/rules/react-doctor/hook-use-state
This example uses a value name that starts with an uppercase letter, preventing the automatic derivation of a `set` setter name. The rule prefers lowercase starting identifiers for state values to ensure a derivable setter name.
```javascript
const [RGB, setRGB] = useState(initialValue);
```
--------------------------------
### Use POST for Data Modifications with Tanstack Start
Source: https://www.react.doctor/docs/rules
Use `createServerFn({ method: 'POST' })` for data modifications to prevent CSRF vulnerabilities, as GET requests can be triggered by prefetching.
```javascript
import { createServerFn } from '@tanstack/start';
const updateData = createServerFn({
method: 'POST',
handler: async ({ data }) => {
// ... update data ...
}
});
```
--------------------------------
### Correct: Using useMemo for Stable Store Initialization
Source: https://www.react.doctor/docs/rules/react-doctor/no-create-store-in-render
This snippet illustrates using `useMemo` to create a stable store instance. The store is created only when its dependencies change, preventing unnecessary re-creation on every render.
```javascript
import { useMemo } from 'react';
import { create } from 'zustand';
function App(props) {
const useStore = useMemo(() => {
return create((set) => ({
// Initialize with props or other stable values
initialValue: props.initialValue,
}));
}, [props.initialValue]); // Dependency array ensures re-creation only when needed
// ... use the store
}
```
--------------------------------
### Incorrect: Non-'on...' Prop with 'handle...' Handler
Source: https://www.react.doctor/docs/rules/react-doctor/jsx-handler-names
This example shows a scenario where a prop that does not start with 'on...' is associated with a 'handle...' prefixed function. This violates the naming convention.
```jsx
```
--------------------------------
### Alternative: useMemo for Recomputable Values
Source: https://www.react.doctor/docs/rules/react-doctor/rerender-lazy-ref-init
If the value can be safely recomputed on remount, consider using `useMemo` for a more concise initialization. This is suitable for values that don't need to persist across remounts.
```javascript
const value = useMemo(() => buildExpensiveCache(), []);
```
--------------------------------
### Example of Correct useMemo Usage
Source: https://www.react.doctor/docs/rules/react-hooks-js/void-use-memo
Demonstrates how to correctly use `useMemo` by assigning its result to a variable and then referencing that variable downstream. This ensures the memoized value is utilized.
```javascript
const sorted = useMemo(() => [...items].sort(), [items]);
return ;
```
--------------------------------
### Example of Number.NaN in useCallback dependency array
Source: https://www.react.doctor/docs/rules/react-doctor/hooks-no-nan-in-deps
This example shows `Number.NaN` used as a dependency in `useCallback`. Similar to the `useEffect` example, this can lead to stale closures or incorrect memoization.
```javascript
const memoizedCallback = useCallback(
() => {
// ...
},
[dep1, Number.NaN],
);
```
--------------------------------
### Valid Script-Qualified HTML lang attribute example
Source: https://www.react.doctor/docs/rules/react-doctor/lang
Example of a correctly set script-qualified 'lang' attribute.
```html
```
--------------------------------
### Correct: Using useRef for Per-Instance Store Initialization
Source: https://www.react.doctor/docs/rules/react-doctor/no-create-store-in-render
When a store genuinely needs to be per-instance, this pattern shows how to initialize it once using `useRef`. This avoids creating a new store on every render while still allowing for instance-specific state.
```javascript
import { useRef } from 'react';
import { create } from 'zustand';
function App() {
const storeRef = useRef();
if (!storeRef.current) {
storeRef.current = create((set) => ({
count: 0,
}));
}
const useStore = storeRef.current;
// ... use the store
}
```
--------------------------------
### Configure Initial Scan in Advisory Mode
Source: https://www.react.doctor/docs/ci-and-prs/github-actions-setup
Use these inputs to run the first scan in advisory mode, reporting issues without failing the check and scanning the entire project.
```yaml
- uses: millionco/react-doctor@v2
with:
blocking: none # or: `warning` or `error`
scope: full # or: `changed`
```
--------------------------------
### Valid Region-Qualified HTML lang attribute example
Source: https://www.react.doctor/docs/rules/react-doctor/lang
Example of a correctly set region-qualified 'lang' attribute.
```html
```
--------------------------------
### Valid HTML lang attribute example
Source: https://www.react.doctor/docs/rules/react-doctor/lang
Example of a correctly set 'lang' attribute on an HTML element.
```html
```
--------------------------------
### Using a Threshold Hook (Optimized)
Source: https://www.react.doctor/docs/rules/react-doctor/rerender-derived-state-from-hook
This optimized example uses a threshold-based hook (`useMediaQuery`) which only triggers a re-render when the specified media query condition changes (e.g., crossing the 767px boundary). This avoids unnecessary re-renders.
```javascript
import { useMediaQuery } from 'react-responsive';
const MyComponent = () => {
// Component re-renders only when the max-width condition changes
const isMobile = useMediaQuery({ maxWidth: 767 });
return
{isMobile ? 'Mobile' : 'Desktop'}
;
};
```
--------------------------------
### Class Component Example
Source: https://www.react.doctor/docs/rules/react-doctor/prefer-function-component
This is an example of a React class component that the rule would flag for potential conversion to a function component.
```javascript
class Foo extends React.Component {
render() {
return
{this.props.foo}
;
}
}
```
--------------------------------
### Class Component Ref with createRef
Source: https://www.react.doctor/docs/rules/react/no-string-refs
Demonstrates the recommended way to handle refs in class components using `createRef` and `ref.current`.
```javascript
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.helloRef = React.createRef();
}
render() {
return ;
}
}
```
--------------------------------
### Parallel Fetching with Promise.all
Source: https://www.react.doctor/docs/rules/react-doctor/tanstack-start-loader-parallel-fetch
Shows the recommended approach for route loaders using `Promise.all` to fetch data concurrently. This significantly improves performance by avoiding sequential request dependencies.
```javascript
const [user, posts] = await Promise.all([fetchUser(id), fetchPosts(id)]);
```
--------------------------------
### JSX Spread Attribute Example
Source: https://www.react.doctor/docs/rules/react-doctor/jsx-props-no-spreading
This is an example of a JSX spread attribute that the rule flags. It passes all properties from the `props` object to the component.
```jsx
```
--------------------------------
### Correct Static Import of Server Functions
Source: https://www.react.doctor/docs/rules/react-doctor/tanstack-start-no-dynamic-server-fn-import
This snippet demonstrates the correct way to import server functions using a static import. This allows the bundler to properly handle server code.
```javascript
import { myFn } from '~/utils/my.functions'
```
--------------------------------
### Undefined Component Example
Source: https://www.react.doctor/docs/rules/react-doctor/jsx-no-undef
This example shows a JSX component 'App' that is not defined in the current scope, triggering the 'jsx-no-undef' error. To fix this, ensure 'App' is imported or declared.
```jsx
```
--------------------------------
### Import and Use Next/Font/Google
Source: https://www.react.doctor/docs/rules/react-doctor/nextjs-no-font-link
Import the desired font from `next/font/google`, configure it with subsets, and apply its class name or variable to your HTML elements. This ensures fonts are self-hosted.
```javascript
import { Inter } from 'next/font/google';
const inter = Inter({
subsets: ['latin']
});
// Apply to body or other elements
{/* ... */}
// Or expose as a CSS variable
{/* ... */}
```
--------------------------------
### Gate Server Action with Session Check (Supabase)
Source: https://www.react.doctor/docs/rules/react-doctor/server-auth-actions
Secure a server action with Supabase authentication. This example fetches the current user and redirects to login if no user is found.
```javascript
import { createServerClient } from "@supabase/ssr";
import { redirect } from "next/navigation";
export const POST = async (request: Request) => {
const supabase = createServerClient(cookies(), env.NEXT_PUBLIC_SUPABASE_URL, env.NEXT_PUBLIC_SUPABASE_ANON_KEY);
const { data: { user } } = await supabase.auth.getUser();
if (!user) {
redirect("/login");
}
// ... rest of your action logic
};
```
--------------------------------
### Move Side Effects from GET to POST Handlers
Source: https://www.react.doctor/docs/rules
Prevent CSRF vulnerabilities by moving side effects from GET handlers to POST handlers. Use a `