AGENTS.md · 24000
`
-
Recycling efficiency: Items with the same type share a recycling pool
-
No layout thrashing: A header never recycles into an image cell
-
Type safety: TypeScript can narrow the item type in each branch
-
Better size estimation: Use
getEstimatedItemSizewithitemTypeforaccurate estimates per type
3. Animation
Impact: HIGH
GPU-accelerated animations, Reanimated patterns, and avoiding render thrashing during gestures.
3.1 Animate Transform and Opacity Instead of Layout Properties
Impact: HIGH (GPU-accelerated animations, no layout recalculation)
Avoid animating width, height, top, left, margin, or padding. These trigger layout recalculation on every frame. Instead, use transform (scale, translate) and opacity which run on the GPU without triggering layout.
Incorrect: animates height, triggers layout every frame
import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated'
function CollapsiblePanel({ expanded }: { expanded: boolean }) {
const animatedStyle = useAnimatedStyle(() => ({
height: withTiming(expanded ? 200 : 0), // triggers layout on every frame
overflow: 'hidden',
}))
return <Animated.View style={animatedStyle}>{children}</Animated.View>
}
Correct: animates scaleY, GPU-accelerated
import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated'
function CollapsiblePanel({ expanded }: { expanded: boolean }) {
const animatedStyle = useAnimatedStyle(() => ({
transform: [
{ scaleY: withTiming(expanded ? 1 : 0) },
],
opacity: withTiming(expanded ? 1 : 0),
}))
return (
<Animated.View style={[{ height: 200, transformOrigin: 'top' }, animatedStyle]}>
{children}
</Animated.View>
)
}
Correct: animates translateY for slide animations
import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated'
function SlideIn({ visible }: { visible: boolean }) {
const animatedStyle = useAnimatedStyle(() => ({
transform: [
{ translateY: withTiming(visible ? 0 : 100) },
],
opacity: withTiming(visible ? 1 : 0),
}))
return <Animated.View style={animatedStyle}>{children}</Animated.View>
}
GPU-accelerated properties: transform (translate, scale, rotate), opacity. Everything else triggers layout.
3.2 Prefer useDerivedValue Over useAnimatedReaction
Impact: MEDIUM (cleaner code, automatic dependency tracking)
When deriving a shared value from another, use useDerivedValue instead of
useAnimatedReaction. Derived values are declarative, automatically track
dependencies, and return a value you can use directly. Animated reactions are
for side effects, not derivations.
Incorrect: useAnimatedReaction for derivation
import { useSharedValue, useAnimatedReaction } from 'react-native-reanimated'
function MyComponent() {
const progress = useSharedValue(0)
const opacity = useSharedValue(1)
useAnimatedReaction(
() => progress.value,
(current) => {
opacity.value = 1 - current
}
)
// ...
}
Correct: useDerivedValue
import { useSharedValue, useDerivedValue } from 'react-native-reanimated'
function MyComponent() {
const progress = useSharedValue(0)
const opacity = useDerivedValue(() => 1 - progress.get())
// ...
}
Use useAnimatedReaction only for side effects that don't produce a value
(e.g., triggering haptics, logging, calling runOnJS).
3.3 Use GestureDetector for Animated Press States
Impact: MEDIUM (UI thread animations, smoother press feedback)
For animated press states (scale, opacity on press), use GestureDetector with
Gesture.Tap() and shared values instead of Pressable's
onPressIn/onPressOut. Gesture callbacks run on the UI thread as worklets—no
JS thread round-trip for press animations.
Incorrect: Pressable with JS thread callbacks
import { Pressable } from 'react-native'
import Animated, {
useSharedValue,
useAnimatedStyle,
withTiming,
} from 'react-native-reanimated'
function AnimatedButton({ onPress }: { onPress: () => void }) {
const scale = useSharedValue(1)
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ scale: scale.value }],
}))
return (
<Pressable
onPress={onPress}
onPressIn={() => (scale.value = withTiming(0.95))}
onPressOut={() => (scale.value = withTiming(1))}
>
<Animated.View style={animatedStyle}>
<Text>Press me</Text>
</Animated.View>
</Pressable>
)
}
Correct: GestureDetector with UI thread worklets
import { Gesture, GestureDetector } from 'react-native-gesture-handler'
import Animated, {
useSharedValue,
useAnimatedStyle,
withTiming,
interpolate,
runOnJS,
} from 'react-native-reanimated'
function AnimatedButton({ onPress }: { onPress: () => void }) {
// Store the press STATE (0 = not pressed, 1 = pressed)
const pressed = useSharedValue(0)
const tap = Gesture.Tap()
.onBegin(() => {
pressed.set(withTiming(1))
})
.onFinalize(() => {
pressed.set(withTiming(0))
})
.onEnd(() => {
runOnJS(onPress)()
})
// Derive visual values from the state
const animatedStyle = useAnimatedStyle(() => ({
transform: [
{ scale: interpolate(withTiming(pressed.get()), [0, 1], [1, 0.95]) },
],
}))
return (
<GestureDetector gesture={tap}>
<Animated.View style={animatedStyle}>
<Text>Press me</Text>
</Animated.View>
</GestureDetector>
)
}
Store the press state (0 or 1), then derive the scale via interpolate.
This keeps the shared value as ground truth. Use runOnJS to call JS functions
from worklets. Use .set() and .get() for React Compiler compatibility.
4. Scroll Performance
Impact: HIGH
Tracking scroll position without causing render thrashing.
4.1 Never Track Scroll Position in useState
Impact: HIGH (prevents render thrashing during scroll)
Never store scroll position in useState. Scroll events fire rapidly—state
updates cause render thrashing and dropped frames. Use a Reanimated shared value
for animations or a ref for non-reactive tracking.
Incorrect: useState causes jank
import { useState } from 'react'
import {
ScrollView,
NativeSyntheticEvent,
NativeScrollEvent,
} from 'react-native'
function Feed() {
const [scrollY, setScrollY] = useState(0)
const onScroll = (e: NativeSyntheticEvent<NativeScrollEvent>) => {
setScrollY(e.nativeEvent.contentOffset.y) // re-renders on every frame
}
return <ScrollView onScroll={onScroll} scrollEventThrottle={16} />
}
Correct: Reanimated for animations
import Animated, {
useSharedValue,
useAnimatedScrollHandler,
} from 'react-native-reanimated'
function Feed() {
const scrollY = useSharedValue(0)
const onScroll = useAnimatedScrollHandler({
onScroll: (e) => {
scrollY.value = e.contentOffset.y // runs on UI thread, no re-render
},
})
return (
<Animated.ScrollView
onScroll={onScroll}
// higher number has better performance, but it fires less often.
// unset this if you need higher precision over performance.
scrollEventThrottle={16}
/>
)
}
Correct: ref for non-reactive tracking
import { useRef } from 'react'
import {
ScrollView,
NativeSyntheticEvent,
NativeScrollEvent,
} from 'react-native'
function Feed() {
const scrollY = useRef(0)
const onScroll = (e: NativeSyntheticEvent<NativeScrollEvent>) => {
scrollY.current = e.nativeEvent.contentOffset.y // no re-render
}
return <ScrollView onScroll={onScroll} scrollEventThrottle={16} />
}
5. Navigation
Impact: HIGH
Using native navigators for stack and tab navigation instead of JS-based alternatives.
5.1 Use Native Navigators for Navigation
Impact: HIGH (native performance, platform-appropriate UI)
Always use native navigators instead of JS-based ones. Native navigators use
platform APIs (UINavigationController on iOS, Fragment on Android) for better
performance and native behavior.
For stacks: Use @react-navigation/native-stack or expo-router's default
stack (which uses native-stack). Avoid @react-navigation/stack.
For tabs: Use react-native-bottom-tabs (native) or expo-router's native
tabs. Avoid @react-navigation/bottom-tabs when native feel matters.
Incorrect: JS stack navigator
import { createStackNavigator } from '@react-navigation/stack'
const Stack = createStackNavigator()
function App() {
return (
<Stack.Navigator>
<Stack.Screen name='Home' component={HomeScreen} />
<Stack.Screen name='Details' component={DetailsScreen} />
</Stack.Navigator>
)
}
Correct: native stack with react-navigation
import { createNativeStackNavigator } from '@react-navigation/native-stack'
const Stack = createNativeStackNavigator()
function App() {
return (
<Stack.Navigator>
<Stack.Screen name='Home' component={HomeScreen} />
<Stack.Screen name='Details' component={DetailsScreen} />
</Stack.Navigator>
)
}
Correct: expo-router uses native stack by default
// app/_layout.tsx
import { Stack } from 'expo-router'
export default function Layout() {
return <Stack />
}
Incorrect: JS bottom tabs
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'
const Tab = createBottomTabNavigator()
function App() {
return (
<Tab.Navigator>
<Tab.Screen name='Home' component={HomeScreen} />
<Tab.Screen name='Settings' component={SettingsScreen} />
</Tab.Navigator>
)
}
Correct: native bottom tabs with react-navigation
import { createNativeBottomTabNavigator } from '@bottom-tabs/react-navigation'
const Tab = createNativeBottomTabNavigator()
function App() {
return (
<Tab.Navigator>
<Tab.Screen
name='Home'
component={HomeScreen}
options={{
tabBarIcon: () => ({ sfSymbol: 'house' }),
}}
/>
<Tab.Screen
name='Settings'
component={SettingsScreen}
options={{
tabBarIcon: () => ({ sfSymbol: 'gear' }),
}}
/>
</Tab.Navigator>
)
}
Correct: expo-router native tabs
// app/(tabs)/_layout.tsx
import { NativeTabs } from 'expo-router/unstable-native-tabs'
export default function TabLayout() {
return (
<NativeTabs>
<NativeTabs.Trigger name='index'>
<NativeTabs.Trigger.Label>Home</NativeTabs.Trigger.Label>
<NativeTabs.Trigger.Icon sf='house.fill' md='home' />
</NativeTabs.Trigger>
<NativeTabs.Trigger name='settings'>
<NativeTabs.Trigger.Label>Settings</NativeTabs.Trigger.Label>
<NativeTabs.Trigger.Icon sf='gear' md='settings' />
</NativeTabs.Trigger>
</NativeTabs>
)
}
On iOS, native tabs automatically enable contentInsetAdjustmentBehavior on the
first ScrollView at the root of each tab screen, so content scrolls correctly
behind the translucent tab bar. If you need to disable this, use
disableAutomaticContentInsets on the trigger.
Incorrect: custom header component
<Stack.Screen
name='Profile'
component={ProfileScreen}
options={{
header: () => <CustomHeader title='Profile' />,
}}
/>
Correct: native header options
<Stack.Screen
name='Profile'
component={ProfileScreen}
options={{
title: 'Profile',
headerLargeTitleEnabled: true,
headerSearchBarOptions: {
placeholder: 'Search',
},
}}
/>
Native headers support iOS large titles, search bars, blur effects, and proper
safe area handling automatically.
-
Performance: Native transitions and gestures run on the UI thread
-
Platform behavior: Automatic iOS large titles, Android material design
-
System integration: Scroll-to-top on tab tap, PiP avoidance, proper safe
areas
-
Accessibility: Platform accessibility features work automatically
6. React State
Impact: MEDIUM
Patterns for managing React state to avoid stale closures and unnecessary re-renders.
6.1 Minimize State Variables and Derive Values
Impact: MEDIUM (fewer re-renders, less state drift)
Use the fewest state variables possible. If a value can be computed from existing state or props, derive it during render instead of storing it in state. Redundant state causes unnecessary re-renders and can drift out of sync.
Incorrect: redundant state
function Cart({ items }: { items: Item[] }) {
const [total, setTotal] = useState(0)
const [itemCount, setItemCount] = useState(0)
useEffect(() => {
setTotal(items.reduce((sum, item) => sum + item.price, 0))
setItemCount(items.length)
}, [items])
return (
<View>
<Text>{itemCount} items</Text>
<Text>Total: ${total}</Text>
</View>
)
}
Correct: derived values
function Cart({ items }: { items: Item[] }) {
const total = items.reduce((sum, item) => sum + item.price, 0)
const itemCount = items.length
return (
<View>
<Text>{itemCount} items</Text>
<Text>Total: ${total}</Text>
</View>
)
}
Another example:
// Incorrect: storing both firstName, lastName, AND fullName
const [firstName, setFirstName] = useState('')
const [lastName, setLastName] = useState('')
const [fullName, setFullName] = useState('')
// Correct: derive fullName
const [firstName, setFirstName] = useState('')
const [lastName, setLastName] = useState('')
const fullName = `${firstName} ${lastName}`
State should be the minimal source of truth. Everything else is derived.
Reference: https://react.dev/learn/choosing-the-state-structure
6.2 Use fallback state instead of initialState
Impact: MEDIUM (reactive fallbacks without syncing)
Use undefined as initial state and nullish coalescing (??) to fall back to
parent or server values. State represents user intent only—undefined means
"user hasn't chosen yet." This enables reactive fallbacks that update when the
source changes, not just on initial render.
Incorrect: syncs state, loses reactivity
type Props = { fallbackEnabled: boolean }
function Toggle({ fallbackEnabled }: Props) {
const [enabled, setEnabled] = useState(defaultEnabled)
// If fallbackEnabled changes, state is stale
// State mixes user intent with default value
return <Switch value={enabled} onValueChange={setEnabled} />
}
Correct: state is user intent, reactive fallback
type Props = { fallbackEnabled: boolean }
function Toggle({ fallbackEnabled }: Props) {
const [_enabled, setEnabled] = useState<boolean | undefined>(undefined)
const enabled = _enabled ?? defaultEnabled
// undefined = user hasn't touched it, falls back to prop
// If defaultEnabled changes, component reflects it
// Once user interacts, their choice persists
return <Switch value={enabled} onValueChange={setEnabled} />
}
With server data:
function ProfileForm({ data }: { data: User }) {
const [_theme, setTheme] = useState<string | undefined>(undefined)
const theme = _theme ?? data.theme
// Shows server value until user overrides
// Server refetch updates the fallback automatically
return <ThemePicker value={theme} onChange={setTheme} />
}
6.3 useState Dispatch updaters for State That Depends on Current Value
Impact: MEDIUM (avoids stale closures, prevents unnecessary re-renders)
When the next state depends on the current state, use a dispatch updater
(setState(prev => ...)) instead of reading the state variable directly in a
callback. This avoids stale closures and ensures you're comparing against the
latest value.
Incorrect: reads state directly
const [size, setSize] = useState<Size | undefined>(undefined)
const onLayout = (e: LayoutChangeEvent) => {
const { width, height } = e.nativeEvent.layout
// size may be stale in this closure
if (size?.width !== width || size?.height !== height) {
setSize({ width, height })
}
}
Correct: dispatch updater
const [size, setSize] = useState<Size | undefined>(undefined)
const onLayout = (e: LayoutChangeEvent) => {
const { width, height } = e.nativeEvent.layout
setSize((prev) => {
if (prev?.width === width && prev?.height === height) return prev
return { width, height }
})
}
Returning the previous value from the updater skips the re-render.
For primitive states, you don't need to compare values before firing a
re-render.
Incorrect: unnecessary comparison for primitive state
const [size, setSize] = useState<Size | undefined>(undefined)
const onLayout = (e: LayoutChangeEvent) => {
const { width, height } = e.nativeEvent.layout
setSize((prev) => (prev === width ? prev : width))
}
Correct: sets primitive state directly
const [size, setSize] = useState<Size | undefined>(undefined)
const onLayout = (e: LayoutChangeEvent) => {
const { width, height } = e.nativeEvent.layout
setSize(width)
}
However, if the next state depends on the current state, you should still use a
dispatch updater.
Incorrect: reads state directly from the callback
const [count, setCount] = useState(0)
const onTap = () => {
setCount(count + 1)
}
Correct: dispatch updater
const [count, setCount] = useState(0)
const onTap = () => {
setCount((prev) => prev + 1)
}
7. State Architecture
Impact: MEDIUM
Ground truth principles for state variables and derived values.
7.1 State Must Represent Ground Truth
Impact: HIGH (cleaner logic, easier debugging, single source of truth)
State variables—both React useState and Reanimated shared values—should
represent the actual state of something (e.g., pressed, progress, isOpen),
not derived visual values (e.g., scale, opacity, translateY). Derive
visual values from state using computation or interpolation.
Incorrect: storing the visual output
const scale = useSharedValue(1)
const tap = Gesture.Tap()
.onBegin(() => {
scale.set(withTiming(0.95))
})
.onFinalize(() => {
scale.set(withTiming(1))
})
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ scale: scale.get() }],
}))
Correct: storing the state, deriving the visual
const pressed = useSharedValue(0) // 0 = not pressed, 1 = pressed
const tap = Gesture.Tap()
.onBegin(() => {
pressed.set(withTiming(1))
})
.onFinalize(() => {
pressed.set(withTiming(0))
})
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ scale: interpolate(pressed.get(), [0, 1], [1, 0.95]) }],
}))
Why this matters:
State variables should represent real "state", not necessarily a desired end
result.
-
Single source of truth — The state (
pressed) describes what'shappening; visuals are derived
-
Easier to extend — Adding opacity, rotation, or other effects just
requires more interpolations from the same state
-
Debugging — Inspecting
pressed = 1is clearer thanscale = 0.95 -
Reusable logic — The same
pressedvalue can drive multiple visualproperties
Same principle for React state:
// Incorrect: storing derived values
const [isExpanded, setIsExpanded] = useState(false)
const [height, setHeight] = useState(0)
useEffect(() => {
setHeight(isExpanded ? 200 : 0)
}, [isExpanded])
// Correct: derive from state
const [isExpanded, setIsExpanded] = useState(false)
const height = isExpanded ? 200 : 0
State is the minimal truth. Everything else is derived.
8. React Compiler
Impact: MEDIUM
Compatibility patterns for React Compiler with React Native and Reanimated.
8.1 Destructure Functions Early in Render (React Compiler)
Impact: HIGH (stable references, fewer re-renders)
This rule is only applicable if you are using the React Compiler.
Destructure functions from hooks at the top of render scope. Never dot into
objects to call functions. Destructured functions are stable references; dotting
creates new references and breaks memoization.
Incorrect: dotting into object
import { useRouter } from 'expo-router'
function SaveButton(props) {
const router = useRouter()
// bad: react-compiler will key the cache on "props" and "router", which are objects that change each render
const handlePress = () => {
props.onSave()
router.push('/success') // unstable reference
}
return <Button onPress={handlePress}>Save</Button>
}
Correct: destructure early
import { useRouter } from 'expo-router'
function SaveButton({ onSave }) {
const { push } = useRouter()
// good: react-compiler will key on push and onSave
const handlePress = () => {
onSave()
push('/success') // stable reference
}
return <Button onPress={handlePress}>Save</Button>
}
8.2 Use .get() and .set() for Reanimated Shared Values (not .value)
Impact: LOW (required for React Compiler compatibility)
With React Compiler enabled, use .get() and .set() instead of reading or
writing .value directly on Reanimated shared values. The compiler can't track
property access—explicit methods ensure correct behavior.
Incorrect: breaks with React Compiler
import { useSharedValue } from 'react-native-reanimated'
function Counter() {
const count = useSharedValue(0)
const increment = () => {
count.value = count.value + 1 // opts out of react compiler
}
return <Button onPress={increment} title={`Count: ${count.value}`} />
}
Correct: React Compiler compatible
import { useSharedValue } from 'react-native-reanimated'
function Counter() {
const count = useSharedValue(0)
const increment = () => {
count.set(count.get() + 1)
}
return <Button onPress={increment} title={`Count: ${count.get()}`} />
}
See the
for more.
9. User Interface
Impact: MEDIUM
Native UI patterns for images, menus, modals, styling, and platform-consistent interfaces.
9.1 Measuring View Dimensions
Impact: MEDIUM (synchronous measurement, avoid unnecessary re-renders)
Use both useLayoutEffect (synchronous) and onLayout (for updates). The sync
measurement gives you the initial size immediately; onLayout keeps it current
when the view changes. For non-primitive states, use a dispatch updater to
compare values and avoid unnecessary re-renders.
Height only:
import { useLayoutEffect, useRef, useState } from 'react'
import { View, LayoutChangeEvent } from 'react-native'
function MeasuredBox({ children }: { children: React.ReactNode }) {
const ref = useRef<View>(null)
const [height, setHeight] = useState<number | undefined>(undefined)
useLayoutEffect(() => {
// Sync measurement on mount (RN 0.82+)
const rect = ref.current?.getBoundingClientRect()
if (rect) setHeight(rect.height)
// Pre-0.82: ref.current?.measure((x, y, w, h) => setHeight(h))
}, [])