15 Prompts for React Native: Components, Navigation, and API Integration

15 Prompts for React Native: Components, Navigation, and API Integration

Introduction

React Native remains one of the most popular frameworks for building cross-platform mobile applications, with over 42% of developers using it according to the 2025 Stack Overflow Developer Survey. As a hands-on developer, you likely rely on AI tools like ChatGPT, Claude, or GitHub Copilot to speed up your workflow. But generic prompts often yield generic results. To get high-quality, production-ready code, you need precise prompts tailored to React Native’s ecosystem.

In this article, I’ll share 15 battle-tested prompts I use daily for building UI components, implementing navigation, and working with APIs. Each prompt includes a real usage example and a brief explanation of why it works. Whether you’re a seasoned React Native developer or just starting out, these prompts will help you ship faster and write cleaner code.

Why Prompt Engineering Matters in React Native

AI models are powerful, but they lack context. A vague prompt like “create a login screen” might give you a functional component, but it won’t consider your specific state management, navigation library, or API layer. By crafting prompts that include constraints, libraries, and expected behavior, you get code that integrates seamlessly into your existing project.

For example, instead of asking “build a button component,” you can specify “build a reusable button component using TypeScript, with loading state and onPress prop, using React Native’s TouchableOpacity.” This saves you from rewriting the generated code later.

Prompts for UI Components

1. Reusable Button Component

Prompt:
"Create a reusable button component in React Native using TypeScript. It should accept props: title (string), onPress (function), variant ('primary'

| 'secondary' | 'outline'), loading (boolean), and disabled (boolean). Use StyleSheet for styling and TouchableOpacity for press handling."

Why it works: This prompt specifies TypeScript, exact props, and styling approach. It produces a component you can drop into any project without modification.

Example output:

import React from 'react';
import { TouchableOpacity, Text, StyleSheet, ActivityIndicator } from 'react-native';

interface ButtonProps {
  title: string;
  onPress: () => void;
variant?: 'primary'

| 'secondary' | 'outline';
  loading?: boolean;
  disabled?: boolean;
}

const Button: React.FC<ButtonProps> = ({ title, onPress, variant = 'primary', loading, disabled }) => {
  const isDisabled = disabled || loading;
  return (
    <TouchableOpacity
      style={[styles.base, styles[variant], isDisabled && styles.disabled]}
      onPress={onPress}
      disabled={isDisabled}
      activeOpacity={0.7}
    >
      {loading ? (
        <ActivityIndicator color={variant === 'outline' ? '#007AFF' : '#FFF'} />
      ) : (
        <Text style={[styles.text, variant === 'outline' && styles.outlineText]}>{title}</Text>
      )}
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  base: { paddingVertical: 12, paddingHorizontal: 24, borderRadius: 8, alignItems: 'center' },
  primary: { backgroundColor: '#007AFF' },
  secondary: { backgroundColor: '#5856D6' },
  outline: { backgroundColor: 'transparent', borderWidth: 1, borderColor: '#007AFF' },
  disabled: { opacity: 0.5 },
  text: { color: '#FFF', fontSize: 16, fontWeight: '600' },
  outlineText: { color: '#007AFF' },
});

export default Button;

2. FlatList with Pull-to-Refresh and Infinite Scroll

Prompt:
"Generate a FlatList component in React Native that fetches data from a paginated API endpoint. It should support pull-to-refresh and infinite scroll. Use useState and useEffect for state management. Include a loading spinner at the bottom when fetching more data."

Why it works: FlatList is the backbone of most list UIs. This prompt covers pagination, refresh, and loading states—common requirements.

Example output:

import React, { useState, useEffect, useCallback } from 'react';
import { FlatList, ActivityIndicator, View, Text, StyleSheet } from 'react-native';

const PaginatedList = () => {
  const [data, setData] = useState([]);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  const fetchData = async (pageNum) => {
    setLoading(true);
    try {
      const response = await fetch(`https://api.example.com/items?page=${pageNum}&limit=20`);
      const json = await response.json();
      if (pageNum === 1) {
        setData(json.results);
      } else {
        setData(prev => [...prev, ...json.results]);
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchData(page); }, [page]);

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    setPage(1);
    await fetchData(1);
    setRefreshing(false);
  }, []);

  const loadMore = () => {
    if (!loading && data.length > 0) {
      setPage(prev => prev + 1);
    }
  };

  const renderFooter = () => loading ? <ActivityIndicator style={{ margin: 20 }} /> : null;

  return (
    <FlatList
      data={data}
      keyExtractor={(item) => item.id.toString()}
      renderItem={({ item }) => <View style={styles.item}><Text>{item.name}</Text></View>}
      onRefresh={onRefresh}
      refreshing={refreshing}
      onEndReached={loadMore}
      onEndReachedThreshold={0.5}
      ListFooterComponent={renderFooter}
    />
  );
};

const styles = StyleSheet.create({ item: { padding: 20, borderBottomWidth: 1, borderColor: '#ccc' } });
export default PaginatedList;

3. Form with Validation

Prompt:
"Create a login form in React Native with email and password fields. Use React Hook Form for form state and Yup for validation. Show inline error messages below each field. Use KeyboardAvoidingView to handle keyboard overlap."

Why it works: React Hook Form and Yup are industry standards. This prompt produces a production-ready form with accessibility and UX best practices.

Prompts for Navigation

4. Stack Navigator Setup

Prompt:
"Write a stack navigator setup using @react-navigation/native and @react-navigation/stack. Include three screens: Home, Profile, and Settings. Configure header styles with a custom color and title font. Use TypeScript for type-safe navigation."

Why it works: Navigation boilerplate is tedious. This prompt generates the exact imports, navigator creation, and screen registration with TypeScript types.

Example output:

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './screens/HomeScreen';
import ProfileScreen from './screens/ProfileScreen';
import SettingsScreen from './screens/SettingsScreen';

export type RootStackParamList = {
  Home: undefined;
  Profile: { userId: string };
  Settings: undefined;
};

const Stack = createStackNavigator<RootStackParamList>();

const AppNavigator = () => (
  <NavigationContainer>
    <Stack.Navigator
      screenOptions={{
        headerStyle: { backgroundColor: '#007AFF' },
        headerTintColor: '#FFF',
        headerTitleStyle: { fontWeight: 'bold' },
      }}
    >
      <Stack.Screen name="Home" component={HomeScreen} />
      <Stack.Screen name="Profile" component={ProfileScreen} />
      <Stack.Screen name="Settings" component={SettingsScreen} />
    </Stack.Navigator>
  </NavigationContainer>
);

export default AppNavigator;

5. Tab Navigator with Badges

Prompt:
"Create a bottom tab navigator using @react-navigation/bottom-tabs. Tabs: Home, Search, Notifications, Profile. Add badge counts on the Notifications tab. Use Ionicons for tab icons. Customize active and inactive colors."

Why it works: Badges and icons are common requirements. This prompt covers both, saving you from reading the docs.

6. Navigation Params Passing

Prompt:
"Show me how to pass parameters from Screen A to Screen B in React Navigation. Screen A should navigate with an object containing id and name. Screen B should read the params and display them. Use TypeScript for type safety."

Prompts for API Integration

7. Custom Hook for Fetching Data

Prompt:
"Write a custom React hook called useFetch that takes a URL and returns { data, loading, error }. Use AbortController to cancel requests when the component unmounts. Handle network errors gracefully."

Why it works: This is a reusable pattern you can apply across projects. Including AbortController prevents memory leaks.

Example output:

import { useState, useEffect, useRef } from 'react';

const useFetch = (url: string) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const abortControllerRef = useRef<AbortController | null>(null);

  useEffect(() => {
    abortControllerRef.current = new AbortController();
    const fetchData = async () => {
      try {
        const response = await fetch(url, { signal: abortControllerRef.current.signal });
        if (!response.ok) throw new Error('Network response was not ok');
        const json = await response.json();
        setData(json);
      } catch (err) {
        if (err.name !== 'AbortError') {
          setError(err.message);
        }
      } finally {
        setLoading(false);
      }
    };
    fetchData();
    return () => abortControllerRef.current?.abort();
  }, [url]);

  return { data, loading, error };
};

export default useFetch;

8. Axios Interceptor for Auth Token

Prompt:
"Create an Axios instance in React Native with request interceptor that adds an Authorization header from AsyncStorage. Add response interceptor to refresh token on 401 errors. Use TypeScript."

Why it works: Token management is a common pain point. This prompt generates a robust solution that handles token refresh automatically.

9. Post Request with Form Data

Prompt:
"Write a function to upload an image to an API endpoint using FormData in React Native. Include the image URI, a name field, and a token in the headers. Handle progress events."

Prompts for State Management

10. Context Provider for Theme

Prompt:
"Create a ThemeContext in React Native that provides light and dark themes. Include a toggle function. Use useColorScheme to detect system preference. Wrap the app with the provider."

11. Redux Toolkit Slice for User

Prompt:
"Generate a Redux Toolkit slice for user state with async thunks for login and logout. Include loading, user, and error states. Use createAsyncThunk."

Prompts for Performance Optimization

12. useMemo and useCallback for Expensive Computations

Prompt:
"Refactor this component to use useMemo for filtered data and useCallback for handlers. Explain why each is necessary."

13. Image Caching with FastImage

Prompt:
"Replace the Image component with react-native-fast-image in a FlatList. Configure priority and cache policy for each image."

Prompts for Testing

14. Unit Test for a Component

Prompt:
"Write a Jest and React Native Testing Library test for the Button component. Test that it renders the title, calls onPress when pressed, and shows ActivityIndicator when loading."

15. Integration Test for Navigation

Prompt:
"Create a test that navigates from HomeScreen to ProfileScreen with params, and verifies that ProfileScreen displays the passed data. Use @react-navigation/native testing utilities."

Conclusion

These 15 prompts are the ones I use most frequently in my React Native projects. They cover the core areas of mobile development: UI components, navigation, API integration, state management, performance, and testing. By being specific about libraries, types, and expected behavior, you can get high-quality code from AI that requires minimal editing.

Remember to always review and test AI-generated code in your environment. Prompts are a starting point—your expertise turns them into production-ready features. Keep experimenting with different phrasings and constraints to find what works best for your workflow.

For more advanced patterns and full-stack integration guides, check out the resources at ASI Biont, where we cover everything from API design to deployment.

← All posts

Comments