Org Skills

React Native screen patterns — working samples

Supporting material for react-native-development. Agents load it on demand; it ships inside the skill folder.

RawSource

The long-form versions of the patterns in SKILL.md. Every sample includes imports and targets Expo SDK 54+, Reanimated 4, FlashList v2.

Sources: https://docs.expo.dev/router/introduction/ · https://shopify.github.io/flash-list/docs/ · https://docs.swmansion.com/react-native-reanimated/docs/ · https://react-hook-form.com/docs/usecontroller/controller

1. Route file and screen

// app/(app)/orders/[id].tsx — the whole route file
export { OrderDetailScreen as default } from '@/features/orders/screens/OrderDetailScreen';

Everything else lives in the feature. The route file stays swappable and the screen stays testable without a router.

2. Detail screen

import { ScrollView, StyleSheet, View } from 'react-native';
import { Stack, useLocalSearchParams } from 'expo-router';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useOrder } from '../api/useOrder';
import { tokens } from '@/shared/theme';

export function OrderDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const { data, isPending, isError, refetch } = useOrder(id);
  const insets = useSafeAreaInsets();

  if (isPending) return <ScreenSkeleton />;
  if (isError) return <ErrorState onRetry={refetch} />;

  return (
    <View style={[styles.root, { paddingBottom: insets.bottom }]}>
      <Stack.Screen options={{ title: data.number }} />
      <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
        <OrderSummary order={data} />
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  root: { flex: 1, backgroundColor: tokens.color.bg },
  content: { padding: tokens.space[4], gap: tokens.space[3] },
});

Insets are applied as padding, not as a SafeAreaView wrapper; inside a navigator that wrapper pads twice, and the core SafeAreaView is deprecated since SDK 54.

3. List screen: pull-to-refresh, infinite scroll, all states

import { useCallback } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { FlashList } from '@shopify/flash-list';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useNetInfo } from '@react-native-community/netinfo';
import { fetchOrders } from '../api/orders';
import { OrderRow } from '../components/OrderRow';
import { tokens } from '@/shared/theme';

export function OrdersScreen() {
  const { isInternetReachable } = useNetInfo();
  const { data, isPending, isError, refetch, isRefetching, fetchNextPage, hasNextPage } = useInfiniteQuery({
    queryKey: ['orders', 'list'],
    queryFn: ({ pageParam, signal }) => fetchOrders({ cursor: pageParam, signal }),
    initialPageParam: undefined as string | undefined,
    getNextPageParam: (last) => last.nextCursor,
  });

  const onEndReached = useCallback(() => { if (hasNextPage) void fetchNextPage(); }, [hasNextPage, fetchNextPage]);

  if (isPending) return <OrdersSkeleton />;
  if (isError) return <ErrorState onRetry={refetch} />;

  const orders = data.pages.flatMap((p) => p.items);

  return (
    <View style={styles.root}>
      {isInternetReachable === false && (
        <Text style={styles.offline} accessibilityLiveRegion="polite">Offline — showing saved orders</Text>
      )}
      <FlashList
        data={orders}
        keyExtractor={(o) => o.id}
        renderItem={({ item }) => <OrderRow id={item.id} number={item.number} total={item.totalLabel} />}
        ItemSeparatorComponent={() => <View style={styles.separator} />}
        ListEmptyComponent={<EmptyOrders />}
        onEndReached={onEndReached}
        onEndReachedThreshold={0.5}
        refreshing={isRefetching}
        onRefresh={refetch}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  root: { flex: 1, backgroundColor: tokens.color.bg },
  offline: { padding: tokens.space[2], backgroundColor: tokens.color.warningBg, color: tokens.color.warningFg },
  separator: { height: StyleSheet.hairlineWidth, backgroundColor: tokens.color.border },
});

Notes: totalLabel is pre-formatted in the API layer — formatting inside renderItem runs on every recycle. OrderRow takes primitives so recycling never re-renders it unnecessarily. No estimatedItemSize: FlashList v2 measures for you.

4. Form with React Hook Form + Zod

import { Controller, useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Keyboard, StyleSheet, Text, TextInput, View } from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-controller';
import { Button } from '@/shared/ui/Button';

const schema = z.object({
  email: z.string().email('Enter a valid email address'),
  note: z.string().max(200).optional(),
});
type Values = z.infer<typeof schema>;

export function ContactForm({ onSubmit }: { onSubmit: (v: Values) => Promise<void> }) {
  const { control, handleSubmit, formState: { errors, isSubmitting } } = useForm<Values>({
    resolver: zodResolver(schema),
    defaultValues: { email: '', note: '' },
  });

  return (
    <KeyboardAwareScrollView contentContainerStyle={styles.form} keyboardShouldPersistTaps="handled">
      <Controller
        control={control}
        name="email"
        render={({ field: { onChange, onBlur, value } }) => (
          <TextInput
            value={value}
            onChangeText={onChange}
            onBlur={onBlur}
            keyboardType="email-address"
            autoCapitalize="none"
            autoComplete="email"
            accessibilityLabel="Email address"
            style={[styles.input, errors.email && styles.inputError]}
          />
        )}
      />
      {errors.email && (
        <Text accessibilityLiveRegion="polite" style={styles.error}>{errors.email.message}</Text>
      )}
      <Button
        label="Send"
        disabled={isSubmitting}
        onPress={handleSubmit(async (values) => { Keyboard.dismiss(); await onSubmit(values); })}
      />
    </KeyboardAwareScrollView>
  );
}

const styles = StyleSheet.create({
  form: { padding: 16, gap: 12 },
  input: { borderWidth: 1, borderRadius: 8, padding: 12, minHeight: 44 },
  inputError: { borderColor: 'crimson' },
  error: { color: 'crimson' },
});

React Native inputs are controlled, so Controller — not register — is the correct wiring. Reuse the same Zod schema on the server.

5. Swipe-to-dismiss with Reanimated 4

import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Animated, { useAnimatedStyle, useSharedValue, withSpring, withTiming } from 'react-native-reanimated';
import { scheduleOnRN } from 'react-native-worklets';
import { useWindowDimensions } from 'react-native';

export function useSwipeToDismiss(onDismiss: () => void) {
  const translateX = useSharedValue(0);
  const { width } = useWindowDimensions();

  const gesture = Gesture.Pan()
    .onChange((e) => { translateX.value += e.changeX; })
    .onEnd((e) => {
      if (Math.abs(translateX.value) > width * 0.35 || Math.abs(e.velocityX) > 800) {
        translateX.value = withTiming(Math.sign(translateX.value) * width, { duration: 180 });
        scheduleOnRN(onDismiss);            // Reanimated 4: replaces runOnJS
      } else {
        translateX.value = withSpring(0);
      }
    });

  const style = useAnimatedStyle(() => ({ transform: [{ translateX: translateX.value }] }));
  return { gesture, style };
}

export function SwipeableCard({ onDismiss, children }: { onDismiss: () => void; children: React.ReactNode }) {
  const { gesture, style } = useSwipeToDismiss(onDismiss);
  return (
    <GestureDetector gesture={gesture}>
      <Animated.View style={style}>{children}</Animated.View>
    </GestureDetector>
  );
}

The app root must be wrapped in GestureHandlerRootView, and react-native-worklets/plugin must be the last entry in babel.config.js.

For a non-gesture transition, skip worklets entirely:

<Animated.View style={{ opacity: visible ? 1 : 0, transitionProperty: 'opacity', transitionDuration: '200ms' }} />

Entering, exiting and reorder animations:

import Animated, { FadeIn, FadeOut, LinearTransition } from 'react-native-reanimated';
<Animated.View entering={FadeIn} exiting={FadeOut} layout={LinearTransition} />

6. Permission flow

import { useCameraPermissions, CameraView } from 'expo-camera';
import { Linking, Text, View } from 'react-native';
import { Button } from '@/shared/ui/Button';

export function ScannerScreen() {
  const [permission, requestPermission] = useCameraPermissions();

  if (!permission) return <ScreenSkeleton />;                       // still loading
  if (!permission.granted) {
    return (
      <View style={{ padding: 16, gap: 12 }}>
        <Text>We use the camera to scan order barcodes. Nothing is uploaded.</Text>
        {permission.canAskAgain
          ? <Button label="Allow camera" onPress={requestPermission} />
          : <Button label="Open settings" onPress={() => Linking.openSettings()} />}
      </View>
    );
  }
  return <CameraView style={{ flex: 1 }} />;
}

Three states, always: undetermined (explain, then ask), denied but askable (ask again), denied permanently (canAskAgain === false → settings). Add the usage strings via the config plugin in app.json; never edit Info.plist directly in a managed project.

7. Storage split

import { MMKV } from 'react-native-mmkv';
import * as SecureStore from 'expo-secure-store';

export const storage = new MMKV();                       // settings, cache flags, last-seen ids
export const saveToken = (t: string) => SecureStore.setItemAsync('access_token', t);
export const readToken = () => SecureStore.getItemAsync('access_token');

MMKV can be given an encryptionKey, but that key must itself be stored somewhere safe — so tokens go directly to expo-secure-store (Keychain / Keystore) and never into MMKV or a persisted store.