AGENTS.md · 48000
const onLayout = (e: LayoutChangeEvent) => { setHeight(e.nativeEvent.layout.height) }
return ( {children} ) }
**Both dimensions:**
```tsx
import { useLayoutEffect, useRef, useState } from 'react'
import { View, LayoutChangeEvent } from 'react-native'
type Size = { width: number; height: number }
function MeasuredBox({ children }: { children: React.ReactNode }) {
const ref = useRef<View>(null)
const [size, setSize] = useState<Size | undefined>(undefined)
useLayoutEffect(() => {
const rect = ref.current?.getBoundingClientRect()
if (rect) setSize({ width: rect.width, height: rect.height })
}, [])
const onLayout = (e: LayoutChangeEvent) => {
const { width, height } = e.nativeEvent.layout
setSize((prev) => {
// for non-primitive states, compare values before firing a re-render
if (prev?.width === width && prev?.height === height) return prev
return { width, height }
})
}
return (
<View ref={ref} onLayout={onLayout}>
{children}
</View>
)
}
Use functional setState to compare—don't read state directly in the callback.
9.2 Modern React Native Styling Patterns
Impact: MEDIUM (consistent design, smoother borders, cleaner layouts)
Follow these styling patterns for cleaner, more consistent React Native code.
Always use borderCurve: 'continuous' with borderRadius:
Use gap instead of margin for spacing between elements:
// Incorrect – margin on children
<View>
<Text style={{ marginBottom: 8 }}>Title</Text>
<Text style={{ marginBottom: 8 }}>Subtitle</Text>
</View>
// Correct – gap on parent
<View style={{ gap: 8 }}>
<Text>Title</Text>
<Text>Subtitle</Text>
</View>
Use padding for space within, gap for space between:
<View style={{ padding: 16, gap: 12 }}>
<Text>First</Text>
<Text>Second</Text>
</View>
Use experimental_backgroundImage for linear gradients:
// Incorrect – third-party gradient library
<LinearGradient colors={['#000', '#fff']} />
// Correct – native CSS gradient syntax
<View
style={{
experimental_backgroundImage: 'linear-gradient(to bottom, #000, #fff)',
}}
/>
Use CSS boxShadow string syntax for shadows:
// Incorrect – legacy shadow objects or elevation
{ shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1 }
{ elevation: 4 }
// Correct – CSS box-shadow syntax
{ boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }
Avoid multiple font sizes – use weight and color for emphasis:
// Incorrect – varying font sizes for hierarchy
<Text style={{ fontSize: 18 }}>Title</Text>
<Text style={{ fontSize: 14 }}>Subtitle</Text>
<Text style={{ fontSize: 12 }}>Caption</Text>
// Correct – consistent size, vary weight and color
<Text style={{ fontWeight: '600' }}>Title</Text>
<Text style={{ color: '#666' }}>Subtitle</Text>
<Text style={{ color: '#999' }}>Caption</Text>
Limiting font sizes creates visual consistency. Use fontWeight (bold/semibold)
and grayscale colors for hierarchy instead.
9.3 Use contentInset for Dynamic ScrollView Spacing
Impact: LOW (smoother updates, no layout recalculation)
When adding space to the top or bottom of a ScrollView that may change
(keyboard, toolbars, dynamic content), use contentInset instead of padding.
Changing contentInset doesn't trigger layout recalculation—it adjusts the
scroll area without re-rendering content.
Incorrect: padding causes layout recalculation
function Feed({ bottomOffset }: { bottomOffset: number }) {
return (
<ScrollView contentContainerStyle={{ paddingBottom: bottomOffset }}>
{children}
</ScrollView>
)
}
// Changing bottomOffset triggers full layout recalculation
Correct: contentInset for dynamic spacing
function Feed({ bottomOffset }: { bottomOffset: number }) {
return (
<ScrollView
contentInset={{ bottom: bottomOffset }}
scrollIndicatorInsets={{ bottom: bottomOffset }}
>
{children}
</ScrollView>
)
}
// Changing bottomOffset only adjusts scroll bounds
Use scrollIndicatorInsets alongside contentInset to keep the scroll
indicator aligned. For static spacing that never changes, padding is fine.
9.4 Use contentInsetAdjustmentBehavior for Safe Areas
Impact: MEDIUM (native safe area handling, no layout shifts)
Use contentInsetAdjustmentBehavior="automatic" on the root ScrollView instead of wrapping content in SafeAreaView or manual padding. This lets iOS handle safe area insets natively with proper scroll behavior.
Incorrect: SafeAreaView wrapper
import { SafeAreaView, ScrollView, View, Text } from 'react-native'
function MyScreen() {
return (
<SafeAreaView style={{ flex: 1 }}>
<ScrollView>
<View>
<Text>Content</Text>
</View>
</ScrollView>
</SafeAreaView>
)
}
Incorrect: manual safe area padding
import { ScrollView, View, Text } from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
function MyScreen() {
const insets = useSafeAreaInsets()
return (
<ScrollView contentContainerStyle={{ paddingTop: insets.top }}>
<View>
<Text>Content</Text>
</View>
</ScrollView>
)
}
Correct: native content inset adjustment
import { ScrollView, View, Text } from 'react-native'
function MyScreen() {
return (
<ScrollView contentInsetAdjustmentBehavior='automatic'>
<View>
<Text>Content</Text>
</View>
</ScrollView>
)
}
The native approach handles dynamic safe areas (keyboard, toolbars) and allows content to scroll behind the status bar naturally.
9.5 Use expo-image for Optimized Images
Impact: HIGH (memory efficiency, caching, blurhash placeholders, progressive loading)
Use expo-image instead of React Native's Image. It provides memory-efficient caching, blurhash placeholders, progressive loading, and better performance for lists.
Incorrect: React Native Image
import { Image } from 'react-native'
function Avatar({ url }: { url: string }) {
return <Image source={{ uri: url }} style={styles.avatar} />
}
Correct: expo-image
import { Image } from 'expo-image'
function Avatar({ url }: { url: string }) {
return <Image source={{ uri: url }} style={styles.avatar} />
}
With blurhash placeholder:
<Image
source={{ uri: url }}
placeholder={{ blurhash: 'LGF5]+Yk^6#M@-5c,1J5@[or[Q6.' }}
contentFit="cover"
transition={200}
style={styles.image}
/>
With priority and caching:
<Image
source={{ uri: url }}
priority="high"
cachePolicy="memory-disk"
style={styles.hero}
/>
Key props:
-
placeholder— Blurhash or thumbnail while loading -
contentFit—cover,contain,fill,scale-down -
transition— Fade-in duration (ms) -
priority—low,normal,high -
cachePolicy—memory,disk,memory-disk,none -
recyclingKey— Unique key for list recycling
For cross-platform (web + native), use SolitoImage from solito/image which uses expo-image under the hood.
Reference: https://docs.expo.dev/versions/latest/sdk/image/
9.6 Use Galeria for Image Galleries and Lightbox
Impact: MEDIUM
For image galleries with lightbox (tap to fullscreen), use @nandorojo/galeria.
It provides native shared element transitions with pinch-to-zoom, double-tap
zoom, and pan-to-close. Works with any image component including expo-image.
Incorrect: custom modal implementation
function ImageGallery({ urls }: { urls: string[] }) {
const [selected, setSelected] = useState<string | null>(null)
return (
<>
{urls.map((url) => (
<Pressable key={url} onPress={() => setSelected(url)}>
<Image source={{ uri: url }} style={styles.thumbnail} />
</Pressable>
))}
<Modal visible={!!selected} onRequestClose={() => setSelected(null)}>
<Image source={{ uri: selected! }} style={styles.fullscreen} />
</Modal>
</>
)
}
Correct: Galeria with expo-image
import { Galeria } from '@nandorojo/galeria'
import { Image } from 'expo-image'
function ImageGallery({ urls }: { urls: string[] }) {
return (
<Galeria urls={urls}>
{urls.map((url, index) => (
<Galeria.Image index={index} key={url}>
<Image source={{ uri: url }} style={styles.thumbnail} />
</Galeria.Image>
))}
</Galeria>
)
}
Single image:
import { Galeria } from '@nandorojo/galeria'
import { Image } from 'expo-image'
function Avatar({ url }: { url: string }) {
return (
<Galeria urls={[url]}>
<Galeria.Image>
<Image source={{ uri: url }} style={styles.avatar} />
</Galeria.Image>
</Galeria>
)
}
With low-res thumbnails and high-res fullscreen:
<Galeria urls={highResUrls}>
{lowResUrls.map((url, index) => (
<Galeria.Image index={index} key={url}>
<Image source={{ uri: url }} style={styles.thumbnail} />
</Galeria.Image>
))}
</Galeria>
With FlashList:
<Galeria urls={urls}>
<FlashList
data={urls}
renderItem={({ item, index }) => (
<Galeria.Image index={index}>
<Image source={{ uri: item }} style={styles.thumbnail} />
</Galeria.Image>
)}
numColumns={3}
estimatedItemSize={100}
/>
</Galeria>
Works with expo-image, SolitoImage, react-native Image, or any image
component.
Reference: https://github.com/nandorojo/galeria
9.7 Use Native Menus for Dropdowns and Context Menus
Impact: HIGH (native accessibility, platform-consistent UX)
Use native platform menus instead of custom JS implementations. Native menus
provide built-in accessibility, consistent platform UX, and better performance.
Use zeego for cross-platform native menus.
Incorrect: custom JS menu
import { useState } from 'react'
import { View, Pressable, Text } from 'react-native'
function MyMenu() {
const [open, setOpen] = useState(false)
return (
<View>
<Pressable onPress={() => setOpen(!open)}>
<Text>Open Menu</Text>
</Pressable>
{open && (
<View style={{ position: 'absolute', top: 40 }}>
<Pressable onPress={() => console.log('edit')}>
<Text>Edit</Text>
</Pressable>
<Pressable onPress={() => console.log('delete')}>
<Text>Delete</Text>
</Pressable>
</View>
)}
</View>
)
}
Correct: native menu with zeego
import * as DropdownMenu from 'zeego/dropdown-menu'
function MyMenu() {
return (
<DropdownMenu.Root>
<DropdownMenu.Trigger>
<Pressable>
<Text>Open Menu</Text>
</Pressable>
</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.Item key='edit' onSelect={() => console.log('edit')}>
<DropdownMenu.ItemTitle>Edit</DropdownMenu.ItemTitle>
</DropdownMenu.Item>
<DropdownMenu.Item
key='delete'
destructive
onSelect={() => console.log('delete')}
>
<DropdownMenu.ItemTitle>Delete</DropdownMenu.ItemTitle>
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
)
}
Context menu: long-press
import * as ContextMenu from 'zeego/context-menu'
function MyContextMenu() {
return (
<ContextMenu.Root>
<ContextMenu.Trigger>
<View style={{ padding: 20 }}>
<Text>Long press me</Text>
</View>
</ContextMenu.Trigger>
<ContextMenu.Content>
<ContextMenu.Item key='copy' onSelect={() => console.log('copy')}>
<ContextMenu.ItemTitle>Copy</ContextMenu.ItemTitle>
</ContextMenu.Item>
<ContextMenu.Item key='paste' onSelect={() => console.log('paste')}>
<ContextMenu.ItemTitle>Paste</ContextMenu.ItemTitle>
</ContextMenu.Item>
</ContextMenu.Content>
</ContextMenu.Root>
)
}
Checkbox items:
import * as DropdownMenu from 'zeego/dropdown-menu'
function SettingsMenu() {
const [notifications, setNotifications] = useState(true)
return (
<DropdownMenu.Root>
<DropdownMenu.Trigger>
<Pressable>
<Text>Settings</Text>
</Pressable>
</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.CheckboxItem
key='notifications'
value={notifications}
onValueChange={() => setNotifications((prev) => !prev)}
>
<DropdownMenu.ItemIndicator />
<DropdownMenu.ItemTitle>Notifications</DropdownMenu.ItemTitle>
</DropdownMenu.CheckboxItem>
</DropdownMenu.Content>
</DropdownMenu.Root>
)
}
Submenus:
import * as DropdownMenu from 'zeego/dropdown-menu'
function MenuWithSubmenu() {
return (
<DropdownMenu.Root>
<DropdownMenu.Trigger>
<Pressable>
<Text>Options</Text>
</Pressable>
</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.Item key='home' onSelect={() => console.log('home')}>
<DropdownMenu.ItemTitle>Home</DropdownMenu.ItemTitle>
</DropdownMenu.Item>
<DropdownMenu.Sub>
<DropdownMenu.SubTrigger key='more'>
<DropdownMenu.ItemTitle>More Options</DropdownMenu.ItemTitle>
</DropdownMenu.SubTrigger>
<DropdownMenu.SubContent>
<DropdownMenu.Item key='settings'>
<DropdownMenu.ItemTitle>Settings</DropdownMenu.ItemTitle>
</DropdownMenu.Item>
<DropdownMenu.Item key='help'>
<DropdownMenu.ItemTitle>Help</DropdownMenu.ItemTitle>
</DropdownMenu.Item>
</DropdownMenu.SubContent>
</DropdownMenu.Sub>
</DropdownMenu.Content>
</DropdownMenu.Root>
)
}
Reference: https://zeego.dev/components/dropdown-menu
9.8 Use Native Modals Over JS-Based Bottom Sheets
Impact: HIGH (native performance, gestures, accessibility)
Use native <Modal> with presentationStyle="formSheet" or React Navigation
v7's native form sheet instead of JS-based bottom sheet libraries. Native modals
have built-in gestures, accessibility, and better performance. Rely on native UI
for low-level primitives.
Incorrect: JS-based bottom sheet
import BottomSheet from 'custom-js-bottom-sheet'
function MyScreen() {
const sheetRef = useRef<BottomSheet>(null)
return (
<View style={{ flex: 1 }}>
<Button onPress={() => sheetRef.current?.expand()} title='Open' />
<BottomSheet ref={sheetRef} snapPoints={['50%', '90%']}>
<View>
<Text>Sheet content</Text>
</View>
</BottomSheet>
</View>
)
}
Correct: native Modal with formSheet
import { Modal, View, Text, Button } from 'react-native'
function MyScreen() {
const [visible, setVisible] = useState(false)
return (
<View style={{ flex: 1 }}>
<Button onPress={() => setVisible(true)} title='Open' />
<Modal
visible={visible}
presentationStyle='formSheet'
animationType='slide'
onRequestClose={() => setVisible(false)}
>
<View>
<Text>Sheet content</Text>
</View>
</Modal>
</View>
)
}
Correct: React Navigation v7 native form sheet
// In your navigator
<Stack.Screen
name='Details'
component={DetailsScreen}
options={{
presentation: 'formSheet',
sheetAllowedDetents: 'fitToContents',
}}
/>
Native modals provide swipe-to-dismiss, proper keyboard avoidance, and
accessibility out of the box.
9.9 Use Pressable Instead of Touchable Components
Impact: LOW (modern API, more flexible)
Never use TouchableOpacity or TouchableHighlight. Use Pressable from
react-native or react-native-gesture-handler instead.
Incorrect: legacy Touchable components
import { TouchableOpacity } from 'react-native'
function MyButton({ onPress }: { onPress: () => void }) {
return (
<TouchableOpacity onPress={onPress} activeOpacity={0.7}>
<Text>Press me</Text>
</TouchableOpacity>
)
}
Correct: Pressable
import { Pressable } from 'react-native'
function MyButton({ onPress }: { onPress: () => void }) {
return (
<Pressable onPress={onPress}>
<Text>Press me</Text>
</Pressable>
)
}
Correct: Pressable from gesture handler for lists
import { Pressable } from 'react-native-gesture-handler'
function ListItem({ onPress }: { onPress: () => void }) {
return (
<Pressable onPress={onPress}>
<Text>Item</Text>
</Pressable>
)
}
Use react-native-gesture-handler Pressable inside scrollable lists for better
gesture coordination, as long as you are using the ScrollView from
react-native-gesture-handler as well.
For animated press states (scale, opacity changes): Use GestureDetector
with Reanimated shared values instead of Pressable's style callback. See the
animation-gesture-detector-press rule.
10. Design System
Impact: MEDIUM
Architecture patterns for building maintainable component libraries.
10.1 Use Compound Components Over Polymorphic Children
Impact: MEDIUM (flexible composition, clearer API)
Don't create components that can accept a string if they aren't a text node. If
a component can receive a string child, it must be a dedicated *Text
component. For components like buttons, which can have both a View (or
Pressable) together with text, use compound components, such a Button,
ButtonText, and ButtonIcon.
Incorrect: polymorphic children
import { Pressable, Text } from 'react-native'
type ButtonProps = {
children: string | React.ReactNode
icon?: React.ReactNode
}
function Button({ children, icon }: ButtonProps) {
return (
<Pressable>
{icon}
{typeof children === 'string' ? <Text>{children}</Text> : children}
</Pressable>
)
}
// Usage is ambiguous
<Button icon={<Icon />}>Save</Button>
<Button><CustomText>Save</CustomText></Button>
Correct: compound components
import { Pressable, Text } from 'react-native'
function Button({ children }: { children: React.ReactNode }) {
return <Pressable>{children}</Pressable>
}
function ButtonText({ children }: { children: React.ReactNode }) {
return <Text>{children}</Text>
}
function ButtonIcon({ children }: { children: React.ReactNode }) {
return <>{children}</>
}
// Usage is explicit and composable
<Button>
<ButtonIcon><SaveIcon /></ButtonIcon>
<ButtonText>Save</ButtonText>
</Button>
<Button>
<ButtonText>Cancel</ButtonText>
</Button>
11. Monorepo
Impact: LOW
Dependency management and native module configuration in monorepos.
11.1 Install Native Dependencies in App Directory
Impact: CRITICAL (required for autolinking to work)
In a monorepo, packages with native code must be installed in the native app's
directory directly. Autolinking only scans the app's node_modules—it won't
find native dependencies installed in other packages.
Incorrect: native dep in shared package only
packages/
ui/
package.json # has react-native-reanimated
app/
package.json # missing react-native-reanimated
Autolinking fails—native code not linked.
Correct: native dep in app directory
// packages/app/package.json
{
"dependencies": {
"react-native-reanimated": "3.16.1"
}
}
Even if the shared package uses the native dependency, the app must also list it
for autolinking to detect and link the native code.
11.2 Use Single Dependency Versions Across Monorepo
Impact: MEDIUM (avoids duplicate bundles, version conflicts)
Use a single version of each dependency across all packages in your monorepo.
Prefer exact versions over ranges. Multiple versions cause duplicate code in
bundles, runtime conflicts, and inconsistent behavior across packages.
Use a tool like syncpack to enforce this. As a last resort, use yarn resolutions
or npm overrides.
Incorrect: version ranges, multiple versions
// packages/app/package.json
{
"dependencies": {
"react-native-reanimated": "^3.0.0"
}
}
// packages/ui/package.json
{
"dependencies": {
"react-native-reanimated": "^3.5.0"
}
}
Correct: exact versions, single source of truth
// package.json (root)
{
"pnpm": {
"overrides": {
"react-native-reanimated": "3.16.1"
}
}
}
// packages/app/package.json
{
"dependencies": {
"react-native-reanimated": "3.16.1"
}
}
// packages/ui/package.json
{
"dependencies": {
"react-native-reanimated": "3.16.1"
}
}
Use your package manager's override/resolution feature to enforce versions at
the root. When adding dependencies, specify exact versions without ^ or ~.
12. Third-Party Dependencies
Impact: LOW
Wrapping and re-exporting third-party dependencies for maintainability.
12.1 Import from Design System Folder
Impact: LOW (enables global changes and easy refactoring)
Re-export dependencies from a design system folder. App code imports from there,
not directly from packages. This enables global changes and easy refactoring.
Incorrect: imports directly from package
import { View, Text } from 'react-native'
import { Button } from '@ui/button'
function Profile() {
return (
<View>
<Text>Hello</Text>
<Button>Save</Button>
</View>
)
}
Correct: imports from design system
import { View } from '@/components/view'
import { Text } from '@/components/text'
import { Button } from '@/components/button'
function Profile() {
return (
<View>
<Text>Hello</Text>
<Button>Save</Button>
</View>
)
}
Start by simply re-exporting. Customize later without changing app code.
13. JavaScript
Impact: LOW
Micro-optimizations like hoisting expensive object creation.
13.1 Hoist Intl Formatter Creation
Impact: LOW-MEDIUM (avoids expensive object recreation)
Don't create Intl.DateTimeFormat, Intl.NumberFormat, or
Intl.RelativeTimeFormat inside render or loops. These are expensive to
instantiate. Hoist to module scope when the locale/options are static.
Incorrect: new formatter every render
function Price({ amount }: { amount: number }) {
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
})
return <Text>{formatter.format(amount)}</Text>
}
Correct: hoisted to module scope
const currencyFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
})
function Price({ amount }: { amount: number }) {
return <Text>{currencyFormatter.format(amount)}</Text>
}
For dynamic locales, memoize:
const dateFormatter = useMemo(
() => new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }),
[locale]
)
Common formatters to hoist:
// Module-level formatters
const dateFormatter = new Intl.DateTimeFormat('en-US', { dateStyle: 'medium' })
const timeFormatter = new Intl.DateTimeFormat('en-US', { timeStyle: 'short' })
const percentFormatter = new Intl.NumberFormat('en-US', { style: 'percent' })
const relativeFormatter = new Intl.RelativeTimeFormat('en-US', {
numeric: 'auto',
})
Creating Intl objects is significantly more expensive than RegExp or plain
objects—each instantiation parses locale data and builds internal lookup tables.
14. Fonts
Impact: LOW
Native font loading for improved performance.