Skip to content

Doko-Demo-Doa/react-native-pdf-editor / .agents/skills/react-native-best-practices

react-native-best-practices

Verified

Provides React Native performance optimization guidelines for FPS, TTI, bundle size, memory leaks, re-renders, and animations. Applies to tasks involving Hermes optimization, JS thread blocking, bridge overhead, FlashList, native modules, or debugging jank and frame drops.

FileKindSize
POWER.mdmarkdown8.8 KB
SKILL.mdskill md14.3 KB
agents/openai.yamlconfig227 B
references/bundle-analyze-app.mdmarkdown5.7 KB
references/bundle-analyze-js.mdmarkdown7.1 KB
references/bundle-barrel-exports.mdmarkdown5.3 KB
references/bundle-code-splitting.mdmarkdown7.4 KB
references/bundle-hermes-mmap.mdmarkdown4.2 KB
references/bundle-library-size.mdmarkdown4.3 KB
references/bundle-native-assets.mdmarkdown5.0 KB
references/bundle-r8-android.mdmarkdown5.4 KB
references/bundle-tree-shaking.mdmarkdown6.0 KB
references/images/bundle-treemap-source-map-explorer.pngbinary651.8 KB
references/images/controlled-textinput-pingpong.pngbinary124.2 KB
references/images/devtools-flamegraph.pngbinary508.5 KB
references/images/emerge-xray-ios.pngbinary429.4 KB
references/images/expo-atlas-treemap.pngbinary604.4 KB
references/images/flashlight-flatlist-vs-flashlist.pngbinary305.9 KB
references/images/fps-drop-graph.pngbinary148.9 KB
references/images/memory-heap-snapshot.pngbinary300.8 KB
references/images/tti-warm-start-diagram.pngbinary124.3 KB
references/images/view-hierarchy-flattening.pngbinary2.5 MB
references/images/xcode-instruments-templates.pngbinary398.8 KB
references/images/xcode-thread-view.pngbinary174.3 KB
references/js-animations-reanimated.mdmarkdown8.4 KB
references/js-atomic-state.mdmarkdown5.4 KB
references/js-bottomsheet.mdmarkdown12.9 KB
references/js-concurrent-react.mdmarkdown6.7 KB
references/js-lists-flatlist-flashlist.mdmarkdown6.4 KB
references/js-measure-fps.mdmarkdown5.3 KB
references/js-memory-leaks.mdmarkdown5.3 KB
references/js-profile-react.mdmarkdown5.9 KB
references/js-react-compiler.mdmarkdown7.2 KB
references/js-uncontrolled-components.mdmarkdown5.5 KB
references/native-android-16kb-alignment.mdmarkdown3.8 KB
references/native-measure-tti.mdmarkdown6.5 KB
references/native-memory-leaks.mdmarkdown5.5 KB
references/native-memory-patterns.mdmarkdown6.3 KB
references/native-platform-setup.mdmarkdown4.1 KB
references/native-profiling.mdmarkdown4.5 KB
references/native-sdks-over-polyfills.mdmarkdown6.8 KB
references/native-threading-model.mdmarkdown8.2 KB
references/native-turbo-modules.mdmarkdown5.8 KB
references/native-view-flattening.mdmarkdown5.2 KB

references/js-react-compiler.md

View on GitHub
---
title: React Compiler
impact: HIGH
tags: memoization, react-compiler, memo, useMemo, useCallback
---

# Skill: React Compiler

Set up React Compiler to automatically memoize components and eliminate unnecessary re-renders.

## Quick Pattern

**Before (manual memoization):**

```jsx
const MemoizedButton = memo(({ onPress }) => <Pressable onPress={onPress} />);
const handler = useCallback(() => doSomething(), []);
```

**After (automatic with React Compiler):**

```jsx
// No memo/useCallback needed - compiler handles it
const Button = ({ onPress }) => <Pressable onPress={onPress} />;
const handler = () => doSomething();
```

## When to Use

- Want automatic performance optimization without manual `memo`/`useMemo`/`useCallback`
- Codebase follows Rules of React
- React Native 0.76+ or Expo SDK 52+
- Ready to remove boilerplate memoization code

## Prerequisites

- Babel-based build system
- Code follows [Rules of React](https://react.dev/reference/rules)
- Check current React Native, Expo, and React Compiler release notes before copying version-specific setup

## Step-by-Step Instructions

### Step 1: Check Compatibility

Before enabling the compiler, verify your project is compatible:

```bash
npx react-compiler-healthcheck@latest
```

This checks if your app follows the Rules of React and identifies potential issues.

### Step 2: Install React Compiler

#### Expo

Use Expo's SDK-specific path:

```bash
# SDK 54 and later: Babel is auto-configured
npx expo install babel-plugin-react-compiler@beta

# SDK 53: install runtime too
npx expo install babel-plugin-react-compiler@beta react-compiler-runtime@beta
```

Then enable the experiment in app config:

```json
{
  "expo": {
    "experiments": {
      "reactCompiler": true
    }
  }
}
```

#### React Native without Expo

```bash
npm install -D babel-plugin-react-compiler@latest
```

For React 17 or 18 targets, also install the compiler runtime:

```bash
npm install react-compiler-runtime@latest
```

Prefer the setup path documented for the app's exact Expo SDK, React Native, and React versions.

### Step 3: Configure Babel (React Native without Expo)

For non-Expo React Native projects, configure Babel manually and keep the compiler first in the plugin pipeline:

```javascript
// babel.config.js
const ReactCompilerConfig = {
  target: '19', // Use '18' for React Native < 0.78
};

module.exports = function (api) {
  api.cache(true);
  return {
    presets: ['module:@react-native/babel-preset'],
    plugins: [
      ['babel-plugin-react-compiler', ReactCompilerConfig],
      // ... other plugins
    ],
  };
};
```

### Step 4: Set Up ESLint (Recommended)

Use the React Hooks/Compiler lint rules that match the app's React version. For Expo, SDK 55+ includes React Compiler lint rules through `eslint-config-expo`; SDK 54 and earlier need `eslint-plugin-react-compiler`. Fix rule violations before treating a component as compiler-optimized; skipped components are safe but do not get the intended memoization.

### Step 5: Verify Optimizations

Verify with `agent-device react-devtools` before/after render measurements. For release-build verification, connect [`@callstack/inspector`](https://github.com/callstackincubator/inspector#inspector) first so React DevTools can attach. Some visual DevTools versions show compiler memoization badges, but profiler evidence is the stable signal.

## Incremental Adoption

You can incrementally adopt React Compiler using two strategies:

### Strategy 1: Limit to Specific Directories

Configure the Babel plugin to only run on specific files, e.g. `src/path/to/dir` in the following examples:

**Expo** (create `babel.config.js` with `npx expo customize babel.config.js`):

```javascript
// babel.config.js
module.exports = function (api) {
  api.cache(true);
  return {
    presets: [
      [
        'babel-preset-expo',
        {
          'react-compiler': {
            sources: (filename) => {
              return filename.includes('src/path/to/dir');
            },
          },
        },
      ],
    ],
  };
};
```

**React Native (without Expo)**:

```javascript
// babel.config.js
const ReactCompilerConfig = {
  target: '19',
  sources: (filename) => {
    return filename.includes('src/path/to/dir');
  },
};

module.exports = function (api) {
  api.cache(true);
  return {
    presets: ['module:@react-native/babel-preset'],
    plugins: [['babel-plugin-react-compiler', ReactCompilerConfig]],
  };
};
```

After changing Babel config, restart Metro with a cleared cache.

### Strategy 2: Opt Out Specific Components

Use the `"use no memo"` directive to skip optimization for specific components or files:

```jsx
function ProblematicComponent() {
  'use no memo';

  return <Text>Will not be optimized</Text>;
}
```

This is useful for temporarily opting out components that cause issues. Fix the underlying problem and remove the directive once resolved.

## Code Examples

### React Compiler Playground

Test transformations at [React Playground](https://playground.react.dev/).

### What Gets Optimized

```jsx
// Components - auto-memoized
const Button = ({ onPress, label }) => (
  <Pressable onPress={onPress}>
    <Text>{label}</Text>
  </Pressable>
);

// Callbacks - auto-cached (no useCallback needed)
const handlePress = () => {
  console.log('pressed');
};

// Expensive computations - auto-cached (no useMemo needed)
const filtered = items.filter((item) => item.active);
```

### What Breaks Compilation

```jsx
// BAD: Mutating props
const BadComponent = ({ items }) => {
  items.push('new item'); // Mutation!
  return <List data={items} />;
};

// BAD: Mutating during render
const BadMutation = () => {
  const [items, setItems] = useState([]);
  items.push('new'); // Mutation during render!
  return <List data={items} />;
};

// BAD: Non-idempotent render
let counter = 0;
const BadRender = () => {
  counter++; // Side effect during render!
  return <Text>{counter}</Text>;
};
```

## Should You Remove Manual Memoization?

Improvements are primarily automatic. You can remove instances of `useCallback`, `useMemo`, and `React.memo` in favor of automatic memoization once the compiler is working correctly in your project.

**Note**: Class components will not be optimized. Migrate to function components for full benefits.

Expo's implementation only runs on application code (not node_modules), and only when bundling for the client (disabled in server rendering).

## Expected Performance Improvements

Expect the largest wins in components that currently rely on manual memoization discipline or have cascading re-renders. Already well-memoized code may show little change; keep the compiler only when profiling or maintenance cost justifies it.

## Common Pitfalls

- **Not fixing ESLint errors first**: When ESLint reports an error, the compiler skips that component—this is safe but means you miss optimization
- **Expecting it to fix bad patterns**: Compiler optimizes good code, doesn't fix bad code
- **Forgetting shallow comparison**: Like `memo`, compiler uses shallow comparison for objects/arrays
- **Not running healthcheck**: Always run `npx react-compiler-healthcheck@latest` before enabling

## Related Skills

- [js-profile-react.md](./js-profile-react.md) - Verify optimization impact
- [js-atomic-state.md](./js-atomic-state.md) - Alternative for state-related re-renders
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 196kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 193kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 193kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 193kUpdated Claude CodeCodexVerifiedInstall