{"slug":"react-native-patterns-2","title":"react-native-patterns","summary":"React Native and Expo app patterns — Expo Router navigation, state separation (server/client/route/form), TanStack Query data fetching with Zod, performant lists, NativeWind/StyleSheet styling, native APIs, and secure storage. Use when building or editing React Native / Expo scre","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-12-02T16:53:47.303855Z","repo":{"url":"https://github.com/beginwithu/agent-skills","stars":11,"forks":2,"license":"MIT","updatedAt":"2026-12-02T16:37:11Z"},"bodyHtml":"<hr>\n<h2>name: react-native-patterns\ndescription: React Native and Expo app patterns — Expo Router navigation, state separation (server/client/route/form), TanStack Query data fetching with Zod, performant lists, NativeWind/StyleSheet styling, native APIs, and secure storage. Use when building or editing React Native / Expo screens, components, navigation, or data layers.\norigin: ECC</h2>\n<h1>React Native / Expo Patterns</h1>\n<p>Practical patterns for building production React Native apps with Expo. Covers navigation, state, data fetching, lists, styling, and native APIs. Pairs with the <code>rules/react-native/</code> ruleset: rules say <em>what</em> to enforce, this skill shows <em>how</em>.</p>\n<p>Libraries named below (NativeWind, Zustand/Jotai, TanStack Query) are common, well-established options shown for illustration — the patterns matter more than the specific package, and any equivalent works. Zod is used for validation to stay consistent with ECC's existing <code>typescript/</code> rules.</p>\n<p>These patterns assume the managed Expo workflow (Expo Router, EAS, <code>expo-*</code> modules) on the New Architecture (the default in recent Expo SDKs, mandatory from SDK 55+). They do NOT assume the browser DOM — React Native has no <code>&lt;div&gt;</code>, no URL bar, and no web data-fetching defaults.</p>\n<h2>When to Activate</h2>\n<p>Use this skill when:</p>\n<ul>\n<li>Building or editing React Native / Expo screens, components, or navigation</li>\n<li>Setting up routing with Expo Router (file-based <code>app/</code> directory)</li>\n<li>Deciding where state belongs (server cache vs client store vs route params vs form)</li>\n<li>Wiring data fetching with TanStack Query and validating responses with Zod</li>\n<li>Rendering long or heavy lists</li>\n<li>Choosing or applying a styling approach (NativeWind or StyleSheet)</li>\n<li>Accessing native device APIs (camera, location, notifications) or secure storage</li>\n<li>Reviewing RN code for mobile-specific issues</li>\n</ul>\n<p>Do NOT use the web/React-DOM patterns here — URL-as-state, <code>&lt;div&gt;</code>, and SWR-for-browser do not apply to React Native.</p>\n<h2>Core Concepts</h2>\n<h3>Project structure (Expo Router)</h3>\n<p>File-based routing under <code>app/</code>. Keep route files thin: they read and validate params, then delegate to a screen component that lives in <code>components/</code> or <code>features/</code>.</p>\n<pre><code>app/\n  _layout.tsx          # root stack\n  (tabs)/\n    _layout.tsx        # tab navigator\n    index.tsx          # Home\n  user/[id].tsx        # dynamic route\ncomponents/\nfeatures/\n  user/UserProfile.tsx\n</code></pre>\n<h3>Navigation: validate route params</h3>\n<p>Deep links and dynamic routes deliver untrusted strings. Validate them with Zod before use.</p>\n<pre><code>// app/user/[id].tsx\nimport { useLocalSearchParams, router } from 'expo-router'\nimport { z } from 'zod'\nimport { UserProfile } from '@/features/user/UserProfile'\n\nconst Params = z.object({ id: z.string().uuid() })\n\nexport default function UserRoute() {\n  const parsed = Params.safeParse(useLocalSearchParams())\n  if (!parsed.success) {\n    router.replace('/not-found')\n    return null\n  }\n  return &lt;UserProfile userId={parsed.data.id} /&gt;\n}\n</code></pre>\n<h3>State: keep concerns separate</h3>\n<p>Do not duplicate server data into a client store. Each concern has its own home.</p>\n<table>\n<thead>\n<tr>\n<th>Concern</th>\n<th>Common choices</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Server state (remote data)</td>\n<td>a server-cache library (TanStack Query, SWR)</td>\n</tr>\n<tr>\n<td>Client/UI state</td>\n<td>a lightweight store (Zustand, Jotai) or Context</td>\n</tr>\n<tr>\n<td>Route/navigation state</td>\n<td>Expo Router params</td>\n</tr>\n<tr>\n<td>Form state</td>\n<td>a form library (e.g. React Hook Form) + schema validation</td>\n</tr>\n<tr>\n<td>Secrets / tokens</td>\n<td><code>expo-secure-store</code></td>\n</tr>\n<tr>\n<td>Non-secret persistence</td>\n<td><code>AsyncStorage</code> / MMKV</td>\n</tr>\n</tbody>\n</table>\n<p>Prefer local <code>useState</code> until state genuinely needs sharing.</p>\n<h3>Data fetching: a cache library + Zod</h3>\n<p>Use a server-cache library (TanStack Query, SWR) instead of fetch-in-<code>useEffect</code>. Validate at the boundary and infer types from the schema. Handle loading, error, and empty states explicitly. (Example uses TanStack Query.)</p>\n<pre><code>import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'\nimport { z } from 'zod'\n\nconst User = z.object({ id: z.string(), email: z.string().email() })\ntype User = z.infer&lt;typeof User&gt;\n\nexport function useUser(id: string) {\n  return useQuery({\n    queryKey: ['user', id],\n    queryFn: async (): Promise&lt;User&gt; =&gt; User.parse(await api.getUser(id)),\n  })\n}\n\nexport function useUpdateEmail(id: string) {\n  const qc = useQueryClient()\n  return useMutation({\n    mutationFn: (email: string) =&gt; api.updateEmail(id, email),\n    onSuccess: () =&gt; qc.invalidateQueries({ queryKey: ['user', id] }),\n  })\n}\n</code></pre>\n<h3>Lists: virtualize, never map a big array in a ScrollView</h3>\n<pre><code>import { FlatList } from 'react-native'\n\n&lt;FlatList\n  data={items}\n  keyExtractor={(item) =&gt; item.id}\n  renderItem={renderItem}          // memoized\n  initialNumToRender={10}\n  windowSize={5}\n/&gt;\n</code></pre>\n<p>Use <code>FlashList</code> (Shopify) for large or heterogeneous lists.</p>\n<h3>Styling: pick one system</h3>\n<p><code>StyleSheet.create()</code> is the framework-native option; utility-class libraries (e.g. NativeWind) are a common alternative. Choose one and stay consistent. Never build style objects inline in JSX on hot paths.</p>\n<pre><code>// NativeWind\n&lt;View className=\"p-4 rounded-2xl bg-white\"&gt;\n  &lt;Text className=\"text-base font-semibold\"&gt;Hello&lt;/Text&gt;\n&lt;/View&gt;\n\n// StyleSheet\nconst styles = StyleSheet.create({ card: { padding: 16, borderRadius: 16, backgroundColor: '#fff' } })\n&lt;View style={styles.card}&gt;...&lt;/View&gt;\n</code></pre>\n<h3>Native APIs: wrap in hooks, clean up effects</h3>\n<p>Keep Expo SDK calls and subscriptions inside <code>use*</code> hooks, not in JSX. Always clean up.</p>\n<pre><code>import { useEffect, useState } from 'react'\nimport * as Location from 'expo-location'\n\ntype LocationState =\n  | { status: 'loading' }\n  | { status: 'denied' }\n  | { status: 'granted'; coords: Location.LocationObjectCoords }\n\nexport function useCurrentLocation() {\n  // Track status, not just coords — so the UI can tell \"still loading\" apart\n  // from \"permission denied\" and show an actionable message.\n  const [state, setState] = useState&lt;LocationState&gt;({ status: 'loading' })\n\n  useEffect(() =&gt; {\n    let active = true\n    ;(async () =&gt; {\n      const { status } = await Location.requestForegroundPermissionsAsync()\n      if (status !== 'granted') {\n        if (active) setState({ status: 'denied' })\n        return\n      }\n      const pos = await Location.getCurrentPositionAsync({})\n      if (active) setState({ status: 'granted', coords: pos.coords })\n    })()\n    return () =&gt; { active = false }   // ignore stale result after unmount\n  }, [])\n\n  return state\n}\n</code></pre>\n<h3>Secure storage for tokens</h3>\n<pre><code>import * as SecureStore from 'expo-secure-store'\n\nawait SecureStore.setItemAsync('auth_token', token)   // Keychain / Keystore\nconst token = await SecureStore.getItemAsync('auth_token')\n</code></pre>\n<h2>Code Examples</h2>\n<h3>A full screen: route → query → list → states</h3>\n<pre><code>// app/(tabs)/orders.tsx\nimport { memo, useCallback } from 'react'\nimport { FlatList, Text, View } from 'react-native'\nimport { useQuery } from '@tanstack/react-query'\nimport { z } from 'zod'\n\nconst OrderSchema = z.object({ id: z.string(), total: z.number(), status: z.string() })\nconst OrdersSchema = z.array(OrderSchema)\ntype Order = z.infer&lt;typeof OrderSchema&gt;\n\nfunction useOrders() {\n  return useQuery({\n    queryKey: ['orders'],\n    queryFn: async () =&gt; OrdersSchema.parse(await api.listOrders()),\n  })\n}\n\n// Memoized so its reference is stable across renders (see the lists guidance).\nconst OrderRow = memo(function OrderRow({ item }: { item: Order }) {\n  return (\n    &lt;View className=\"px-4 py-3 border-b border-neutral-200\"&gt;\n      &lt;Text className=\"font-medium\"&gt;#{item.id}&lt;/Text&gt;\n      &lt;Text className=\"text-neutral-500\"&gt;{item.status} · ${item.total}&lt;/Text&gt;\n    &lt;/View&gt;\n  )\n})\n\nexport default function OrdersScreen() {\n  const { data, isLoading, isError, refetch, isRefetching } = useOrders()\n  const renderItem = useCallback(({ item }: { item: Order }) =&gt; &lt;OrderRow item={item} /&gt;, [])\n\n  if (isLoading) return &lt;Centered&gt;&lt;Text&gt;Loading…&lt;/Text&gt;&lt;/Centered&gt;\n  if (isError) return &lt;Centered&gt;&lt;Text accessibilityRole=\"alert\"&gt;Could not load orders.&lt;/Text&gt;&lt;/Centered&gt;\n  if (!data?.length) return &lt;Centered&gt;&lt;Text&gt;No orders yet.&lt;/Text&gt;&lt;/Centered&gt;\n\n  return (\n    &lt;FlatList\n      data={data}\n      keyExtractor={(o) =&gt; o.id}\n      onRefresh={refetch}\n      refreshing={isRefetching}\n      renderItem={renderItem}\n    /&gt;\n  )\n}\n</code></pre>\n<h3>A form: React Hook Form + Zod resolver</h3>\n<pre><code>import { useForm, Controller } from 'react-hook-form'\nimport { zodResolver } from '@hookform/resolvers/zod'\nimport { z } from 'zod'\nimport { TextInput, Button, Text } from 'react-native'\n\nconst Schema = z.object({ email: z.string().email('Invalid email') })\ntype FormValues = z.infer&lt;typeof Schema&gt;\n\nexport function EmailForm({ onSubmit }: { onSubmit: (v: FormValues) =&gt; void }) {\n  const { control, handleSubmit, formState: { errors } } = useForm&lt;FormValues&gt;({\n    resolver: zodResolver(Schema),\n    defaultValues: { email: '' },\n  })\n\n  return (\n    &lt;&gt;\n      &lt;Controller\n        control={control}\n        name=\"email\"\n        render={({ field: { value, onChange, onBlur } }) =&gt; (\n          &lt;TextInput\n            value={value}\n            onChangeText={onChange}\n            onBlur={onBlur}\n            autoCapitalize=\"none\"\n            keyboardType=\"email-address\"\n            accessibilityLabel=\"Email address\"\n          /&gt;\n        )}\n      /&gt;\n      {errors.email &amp;&amp; &lt;Text accessibilityRole=\"alert\"&gt;{errors.email.message}&lt;/Text&gt;}\n      &lt;Button title=\"Save\" onPress={handleSubmit(onSubmit)} /&gt;\n    &lt;/&gt;\n  )\n}\n</code></pre>\n<h2>Anti-Patterns</h2>\n<pre><code>// WRONG: large array mapped inside a ScrollView (no virtualization, janky, high memory)\n&lt;ScrollView&gt;{items.map((i) =&gt; &lt;Row key={i.id} item={i} /&gt;)}&lt;/ScrollView&gt;\n// RIGHT: FlatList / FlashList\n\n// WRONG: server data copied into a client store (two sources of truth, stale data)\nconst useStore = create((set) =&gt; ({ users: [], setUsers: (u) =&gt; set({ users: u }) }))\nuseEffect(() =&gt; { getUsers().then(setUsers) }, [])\n// RIGHT: useQuery owns server state; derive what you need\n\n// WRONG: tokens in AsyncStorage (not encrypted)\nawait AsyncStorage.setItem('auth_token', token)\n// RIGHT: expo-secure-store\n\n// WRONG: trusting deep-link params\nconst { id } = useLocalSearchParams(); fetchUser(id)\n// RIGHT: validate with Zod before use\n\n// WRONG: inline style object recreated every render on a hot path\n&lt;View style={{ padding: 16, backgroundColor: '#fff' }} /&gt;\n// RIGHT: StyleSheet.create at module scope, or NativeWind className\n\n// WRONG: real secret shipped in the bundle\nconst STRIPE_SECRET = 'sk_live_...'\n// RIGHT: keep privileged calls server-side; ship only public keys protected by backend rules\n</code></pre>\n<h2>Best Practices</h2>\n<ul>\n<li>Keep route files thin; put logic in screen components and <code>use*</code> hooks.</li>\n<li>Validate every external input (API responses, route params, push payloads) with Zod.</li>\n<li>Let TanStack Query own server state; keep client stores small.</li>\n<li>Always render loading, error, and empty states — never just a spinner with no fallback.</li>\n<li>Virtualize lists; memoize <code>renderItem</code>; provide a stable <code>keyExtractor</code>.</li>\n<li>Use <code>react-native-reanimated</code> for animation (UI thread); avoid heavy work on the JS thread.</li>\n<li>Store tokens in <code>expo-secure-store</code>; never trust the client for authorization.</li>\n<li>Respect safe areas, Dynamic Type, and accessibility roles/labels from the start.</li>\n<li>Confirm New Architecture compatibility for every native dependency before release.</li>\n</ul>\n<h2>Related Skills</h2>\n<ul>\n<li><code>frontend-patterns</code> — React/Next.js (web) patterns; useful for shared React concepts, but DOM-specific.</li>\n<li><code>coding-standards</code> — TypeScript/JavaScript idioms that apply to RN code.</li>\n<li><code>tdd-workflow</code>, <code>e2e-testing</code> — testing process (use Jest + React Native Testing Library, Maestro/Detox for RN).</li>\n<li><code>security-review</code> — general security checklist that complements the RN bundle/secret guidance above.</li>\n</ul>\n","files":[{"path":"LICENSE","sizeBytes":1071,"isText":false},{"path":"SKILL.md","sizeBytes":11752,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-12-02T16:57:58.530533Z","sha256":"7E55F58D2C72D76505A0F2E9781A70696487377D3B8F0547387141D06E7AFDBD","sizeBytes":5692},"review":null,"source":{"repositoryUrl":"https://github.com/beginwithu/agent-skills","path":"skills/react-native-patterns","license":"MIT","commit":"a960304c52212f2e845067047f5cefc0c594d787","subtreeSha":"350D37137A590925B306B5B7A43DC409A87878BF3849CD445907FB4B2295A880","lastSyncedAt":"2026-12-02T16:52:59.20206Z"},"reviewedAt":"2026-12-02T17:06:14.934498Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/beginwithu/agent-skills/tree/main/skills/react-native-patterns"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install beginwithu-agent-skills@llmmart"},{"target":"git","command":"git clone https://github.com/beginwithu/agent-skills.git"}]}