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-uncontrolled-components.md

View on GitHub
---
title: Uncontrolled Components
impact: HIGH
tags: textinput, forms, controlled, uncontrolled
---

# Skill: Uncontrolled Components

Fix TextInput synchronization and flickering issues by using the uncontrolled component pattern where React does not need to own every keystroke.

## Quick Pattern

**Before (controlled - may flicker on legacy arch):**

```jsx
<TextInput value={text} onChangeText={setText} />
```

**After (uncontrolled - native owns state):**

```jsx
<TextInput defaultValue={text} onChangeText={setText} />
```

## When to Use

- TextInput flickers or shows wrong characters during fast typing
- Text input lags behind user input on low-end devices
- Using legacy (non-New Architecture) React Native
- Need maximum input responsiveness
- React does not need to transform, mask, validate, or own the value on every keystroke

## Prerequisites

- Understanding of React controlled vs uncontrolled components
- TextInput component in use

## Problem Description

![Controlled TextInput Ping-Pong Communication](images/controlled-textinput-pingpong.png)

The diagram shows what happens when typing "TEST" with a controlled `TextInput`:

1. User types "T" → `onChangeText('T')` fires
2. React calls `setValue('T')` → native updates to "T"
3. User types "E" → `onChangeText('TE')` fires
4. React calls `setValue('TE')` → native updates to "TE"
5. ...continues for each character

**The problem**: Each character requires a round-trip between native and JavaScript. On legacy architecture, if React state update is slow, native may show intermediate states (flicker).

**New Architecture note:** This issue is largely resolved in New Architecture, but uncontrolled pattern still provides best performance.

Use uncontrolled TextInput primarily as a responsiveness or legacy-architecture escape hatch. Keep controlled inputs when React must transform, mask, validate, or own the value on every keystroke.

## Step-by-Step Instructions

### 1. Identify Controlled TextInput

```jsx
// Controlled - value prop syncs state to native
const ControlledInput = () => {
  const [value, setValue] = useState('');

  return (
    <TextInput
      value={value} // This causes sync issues
      onChangeText={setValue}
    />
  );
};
```

### 2. Convert to Uncontrolled

Remove the `value` prop to make it uncontrolled:

```jsx
// Uncontrolled - native owns the state
const UncontrolledInput = () => {
  const [value, setValue] = useState('');

  return (
    <TextInput
      defaultValue={value} // Only sets initial value
      onChangeText={setValue} // Still updates React state
    />
  );
};
```

### 3. Use Ref for Programmatic Control

If you need to read/set value programmatically:

```jsx
const UncontrolledWithRef = () => {
  const inputRef = useRef(null);

  const clearInput = () => {
    inputRef.current?.clear();
  };

  const getValue = () => {
    // Use onChangeText to track value, or native methods
  };

  return (
    <TextInput
      ref={inputRef}
      defaultValue=""
      onChangeText={(text) => console.log('Current:', text)}
    />
  );
};
```

## Code Examples

### Full Migration Example

**Before (Controlled):**

```jsx
const SearchInput = () => {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);

  const handleChange = (text) => {
    setQuery(text);
    fetchResults(text).then(setResults);
  };

  return (
    <View>
      <TextInput
        value={query} // Remove this
        onChangeText={handleChange}
        placeholder="Search..."
      />
      <ResultsList data={results} />
    </View>
  );
};
```

**After (Uncontrolled):**

```jsx
const SearchInput = () => {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);

  const handleChange = (text) => {
    setQuery(text);
    fetchResults(text).then(setResults);
  };

  return (
    <View>
      <TextInput
        defaultValue="" // Initial value only
        onChangeText={handleChange}
        placeholder="Search..."
      />
      <ResultsList data={results} />
    </View>
  );
};
```

### When You Need Value Control

For input masking or validation that modifies input:

```jsx
// Option 1: Accept the controlled behavior (may flicker)
const MaskedInput = () => {
  const [value, setValue] = useState('');

  const handleChange = (text) => {
    // Phone mask: (123) 456-7890
    const masked = maskPhone(text);
    setValue(masked);
  };

  return (
    <TextInput
      value={value} // Necessary for masking
      onChangeText={handleChange}
    />
  );
};

// Option 2: Use a native masked input library
// react-native-masked-text handles this natively
```

## Decision Matrix

| Scenario                           | Recommendation               |
| ---------------------------------- | ---------------------------- |
| Simple text input                  | Uncontrolled                 |
| Search/filter input                | Uncontrolled                 |
| Form with validation on submit     | Uncontrolled                 |
| Input masking (phone, credit card) | Controlled or native library |
| Character-by-character validation  | Controlled                   |
| New Architecture app               | Either works well            |

## Common Pitfalls

- **Forgetting `defaultValue`**: Without it, input starts empty
- **Trying to clear with state**: Use `ref.current.clear()` instead
- **Mixing patterns**: Don't use both `value` and `defaultValue`

## Related Skills

- [js-profile-react.md](./js-profile-react.md) - Profile input performance
- [js-concurrent-react.md](./js-concurrent-react.md) - Defer expensive search operations
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: 197kUpdated 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: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated 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: 194kUpdated Claude CodeCodexVerifiedInstall