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-atomic-state.md

View on GitHub
---
title: Atomic State Management
impact: HIGH
tags: state, jotai, zustand, re-renders, context
---

# Skill: Atomic State Management

Use atomic state libraries (Jotai, Zustand) to reduce unnecessary re-renders without manual memoization.

## Quick Pattern

**Before (broad Context value):**

```jsx
const { filter, todos } = useContext(TodoContext);
// Re-renders when the provider value identity changes
```

**After (Zustand - only subscribed state):**

```jsx
const filter = useTodoStore((s) => s.filter);
// Only re-renders when filter changes
```

## When to Use

- Global state changes cause widespread re-renders
- Using React Context for app state
- Components re-render even when their data hasn't changed
- Want to avoid manual `useMemo`/`useCallback` everywhere
- Not ready to adopt React Compiler

## Prerequisites

- State management library: `jotai` or `zustand`

```bash
npm install jotai
# or
npm install zustand
```

## Problem Description

Context is not inherently slow, but a broad provider value makes every consumer of that context eligible to re-render when the value identity changes. Atomic stores help when profiling shows unrelated subscribers rendering after global state updates.

## Step-by-Step Instructions

### Using Jotai

#### 1. Define Atoms

```jsx
import { atom } from 'jotai';

// Each atom is an independent piece of state
const filterAtom = atom('all');
const todosAtom = atom([]);

// Derived atom (computed value)
const filteredTodosAtom = atom((get) => {
  const filter = get(filterAtom);
  const todos = get(todosAtom);

  if (filter === 'active') return todos.filter((t) => !t.completed);
  if (filter === 'completed') return todos.filter((t) => t.completed);
  return todos;
});
```

#### 2. Use Atoms in Components

```jsx
import { useAtom, useAtomValue, useSetAtom } from 'jotai';

// Only re-renders when filterAtom changes
const FilterMenu = () => {
  const [filter, setFilter] = useAtom(filterAtom);

  return (
    <View>
      {['all', 'active', 'completed'].map((f) => (
        <Pressable key={f} onPress={() => setFilter(f)}>
          <Text style={filter === f ? styles.active : null}>{f}</Text>
        </Pressable>
      ))}
    </View>
  );
};

// Only re-renders when todosAtom changes
const TodoItem = ({ id }) => {
  const setTodos = useSetAtom(todosAtom); // Only setter, no re-render on read

  const toggleTodo = () => {
    setTodos((prev) =>
      prev.map((t) => (t.id === id ? { ...t, completed: !t.completed } : t))
    );
  };

  return <Pressable onPress={toggleTodo}>...</Pressable>;
};
```

### Using Zustand

#### 1. Create Store

```jsx
import { create } from 'zustand';

const useTodoStore = create((set, get) => ({
  filter: 'all',
  todos: [],

  setFilter: (filter) => set({ filter }),

  toggleTodo: (id) =>
    set((state) => ({
      todos: state.todos.map((t) =>
        t.id === id ? { ...t, completed: !t.completed } : t
      ),
    })),

  // Selector for derived state
  getFilteredTodos: () => {
    const { filter, todos } = get();
    if (filter === 'active') return todos.filter((t) => !t.completed);
    if (filter === 'completed') return todos.filter((t) => t.completed);
    return todos;
  },
}));
```

#### 2. Use Selectors

```jsx
// Only re-renders when filter changes
const FilterMenu = () => {
  const filter = useTodoStore((state) => state.filter);
  const setFilter = useTodoStore((state) => state.setFilter);

  return (
    <View>
      {['all', 'active', 'completed'].map((f) => (
        <Pressable key={f} onPress={() => setFilter(f)}>
          <Text>{f}</Text>
        </Pressable>
      ))}
    </View>
  );
};

// Only re-renders when todos change
const TodoList = () => {
  const todos = useTodoStore((state) => state.todos);
  return todos.map((todo) => <TodoItem key={todo.id} {...todo} />);
};
```

## Comparison

| Feature         | Context                             | Jotai            | Zustand              |
| --------------- | ----------------------------------- | ---------------- | -------------------- |
| Re-render scope | Consumers of changed provider value | Atom subscribers | Selector subscribers |
| Derived state   | Manual                              | Built-in atoms   | Selectors            |
| DevTools        | React DevTools                      | Jotai DevTools   | Zustand DevTools     |
| Bundle size     | 0 KB                                | Small dependency | Small dependency     |
| Learning curve  | Low                                 | Medium           | Low                  |

## When to Use Which

Do not migrate global state solely for fewer re-renders if React Compiler or narrower subscriptions solve the measured issue. Atomic state helps when broad Context/store updates cause unrelated subscribers to render.

- **Jotai**: Fine-grained state, many small atoms, derived/async atoms
- **Zustand**: Simpler mental model, single store, familiar Redux-like pattern
- **React Compiler**: If available, may eliminate need for these libraries

## Common Pitfalls

- **Over-atomizing**: Don't create an atom for every variable. Group related state.
- **Missing selectors in Zustand**: Always use selectors to prevent unnecessary re-renders.
- **Derived state without memoization**: Use derived atoms (Jotai) or memoized selectors.

## Related Skills

- [js-bottomsheet.md](./js-bottomsheet.md) - Avoid context-driven bottom sheet subtree re-renders
- [js-react-compiler.md](./js-react-compiler.md) - Automatic memoization alternative
- [js-profile-react.md](./js-profile-react.md) - Verify re-render reduction
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