10 Prompts for React Native: Components, Navigation & API

10 Prompts for React Native: Components, Navigation & API

React Native is a top choice for cross-platform apps, but writing boilerplate takes time. AI prompts help you generate production-ready components in seconds. Here are 10 prompts I use daily. Examples follow React Native 0.74 and React Navigation 6.

1. TypeScript Functional Component

Prompt: "Act as a senior RN developer. Write a TypeScript functional component that fetches data from a URL, handles loading and error states, and renders a FlatList. Use proper types and error handling."

Usage: Paste the prompt, add your URL and item type. The AI returns a reusable component.

function FetchList<T>({ url, renderItem }: { url: string; renderItem: (item: T) => ReactElement }) {
  const [data, setData] = useState<T[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);
  useEffect(() => {
    fetch(url).then(r => r.json()).then(setData)
      .catch(setError).finally(() => setLoading(false));
  }, [url]);
  if (loading) return <ActivityIndicator />;
  if (error) return <Text>Error: {error.message}</Text>;
  return <FlatList data={data} keyExtractor={(_, i) => i.toString()} renderItem={({ item }) => renderItem(item)} />;
}

2. Custom API Hook

Prompt: "Create a custom hook useApi that wraps fetch with AbortController to cancel requests on unmount. Return { data, error, isLoading, refetch } and accept a method parameter."

Usage: Centralizes API logic for any screen.

export const useApi = (url: string, method = 'GET') => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [isLoading, setLoading] = useState(true);
  const ref = useRef<AbortController | null>(null);
  const fetchData = useCallback(async () => {
    ref.current?.abort(); ref.current = new AbortController();
    setLoading(true);
    try { const res = await fetch(url, { method, signal: ref.current.signal }); setData(await res.json()); }
    catch (e) { setError(e); } finally { setLoading(false); }
  }, [url, method]);
  useEffect(() => () => ref.current?.abort(), []);
  return { data, error, isLoading, refetch: fetchData };
};

3. StyleSheet Layout

Prompt: "Generate a StyleSheet for a loading screen with a logo, spinner, and progress text. Use flexbox and design tokens."

Usage: Produces clean styles to adapt to your theme.

export const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  logo: { width: 80, height: 80, marginBottom: 24 },
  text: { color: '#F8FAFC', fontSize: 16 },
});

4. Navigation Stack

Prompt: "Write a React Navigation v6 native stack with Home, Details, and Settings screens. Include TypeScript navigation types."

Usage: Verify with the official React Navigation docs.

export type RootStackParamList = { Home: undefined; Details: { itemId: number }; Settings: undefined };
const Stack = createNativeStackNavigator<RootStackParamList>();
export const AppNavigator = () => (
  <NavigationContainer>
    <Stack.Navigator>
      <Stack.Screen name="Home" component={HomeScreen} />
      <Stack.Screen name="Details" component={DetailsScreen} />
      <Stack.Screen name="Settings" component={SettingsScreen} />
    </Stack.Navigator>
  </NavigationContainer>
);

5. Form Validation

Prompt: "Build a registration form with Formik and Yup. Include email, password, and confirmation. Show errors under inputs and call an API on submit."

Usage: A fast start for any form.

const schema = Yup.object().shape({
  email: Yup.string().email().required(),
  password: Yup.string().min(6).required(),
  confirm: Yup.string().oneOf([Yup.ref('password')]).required(),
});
<Formik initialValues={{ email: '', password: '', confirm: '' }} validationSchema={schema} onSubmit={post('/register')}>
  {({ handleSubmit, errors }) => (
    <>
      <Field name="email" />
      {errors.email && <Text>{errors.email}</Text>}
      <Button onPress={handleSubmit} title="Sign up" />
    </>
  )}
</Formik>

6. FlatList Performance

Prompt: "Explain and optimize a FlatList rendering 10,000 rows. Include getItemLayout, removeClippedSubviews, and windowSize."

Usage: Improves any long list.

<FlatList data={items} renderItem={renderItem} keyExtractor={i => i.id}
  getItemLayout={(_, i) => ({ length: ITEM_HEIGHT, offset: ITEM_HEIGHT * i, index: i })}
  removeClippedSubviews windowSize={10} maxToRenderPerBatch={10} initialNumToRender={10} />

7. Environment Variables

Prompt: "Set up react-native-config with a .env file, env.d.ts for TypeScript, and an example import."

Usage: Keeps API keys out of source control.

# .env
API_URL=https://api.example.com
API_KEY=sk_live_123
import Config from 'react-native-config';
const url = Config.API_URL;

8. Animated Splash

Prompt: "Create a fade-in splash screen with Animated, then call navigation.replace('Home')."

Usage: A clean effect without native libraries.

const opacity = useRef(new Animated.Value(0)).current;
useEffect(() => {
  Animated.timing(opacity, { toValue: 1, duration: 800, useNativeDriver: true }).start(() => navigation.replace('Home'));
}, []);
return <Animated.View style={{ flex: 1, opacity }} />;

9. Unit Test

Prompt: "Write a Jest test for the FetchList component. Mock fetch and assert loading, success, and error states."

Usage: Get test coverage quickly.

global.fetch = jest.fn().mockResolvedValue({ json: async () => [{ id: 1 }] });
const { getByText } = render(<FetchList url="/data" renderItem={({ item }) => <Text>{item.id}</Text>} />);
await waitFor(() => expect(getByText('1')).toBeTruthy());

10. JS to TS Migration

Prompt: "Act as a migration engineer. Convert this JS component to TypeScript, adding interfaces for props."

Usage: Paste your JS code and get fully typed TSX.

type User = { name: string; email: string };
export const UserCard = ({ user }: { user: User }) => (
  <View><Text>{user.name}</Text><Text>{user.email}</Text></View>
);

Summary

AI prompts don't replace senior engineers—they remove repetitive work. Use these as starting points, review the output, and adapt to your stack. Try one prompt in your next task and see the difference.

For more React Native insights, visit asibiont.com/blog. Happy coding!

← All posts

Comments