React Native Mobile
What is the purpose of `react-native-gesture-handler`?
It provides a native-driven gesture system that recognizes taps, pans, swipes, pinches, and rotation directly on the UI thread, bypassing the JavaScript bridge. It is required by React Navigation for native stack transitions and enables smooth, responsive gesture interactions.
AsyncStorage is an unencrypted, asynchronous key-value store similar to localStorage, suitable for non-sensitive data like user preferences. SecureStore (Expo) uses the iOS Keychain and Android Keystore to encrypt sensitive data like tokens and passwords.
`Suspense` lets components wait for asynchronous resources (like lazy-loaded components or data) before rendering. It displays a fallback UI, typically a loading indicator, while children are suspended, and unmounts it once the children are ready to render.
Use WatermelonDB or SQLite with an outbox pattern: write mutations locally first, queue sync operations, then push to server when connectivity returns via NetInfo. Resolve conflicts using timestamps or version vectors server-side.
React Native Mobile
What is the difference between padding and margin in React Native styles?
Call navigation.navigate('RouteName', { itemId: 86, otherParam: 'anything' }). The receiving screen accesses parameters via the route prop: const { itemId } = route.params; In TypeScript, declare the param list in the navigator's generic type.
The Animated API creates smooth, declarative animations for opacity, position, scale, and other style values. Use Animated.timing for duration-based, Animated.spring for physics-based, and Animated.Value or Animated.ValueXY as drivers. It's being supplemented by Reanimated for better UI thread performance.
Padding is the space inside the component's border between the border and content. Margin is the space outside the component, separating it from siblings. Both accept numbers (density-independent pixels) or strings with units.
Use the Dimensions API with addEventListener('change') to react to size changes, or use onLayout on the root view. Lock orientation with expo-screen-orientation or Info.plist/android:screenOrientation for full control of supported orientations.
React Native Mobile
What is the purpose of AppState in React Native?
AppState tells you whether the app is in 'active', 'background', or 'inactive' (iOS only) state. Subscribe with AppState.addEventListener('change', handler) to pause/resume animations, save data when backgrounded, or refresh content when foregrounded.
It opens a URL in the appropriate native application, such as launching a web browser, opening the phone dialer with a `tel:` link, composing an email with a `mailto:` link, or navigating to another app via a custom URL scheme.
Use expo-updates: run 'eas update:configure', then 'eas update --branch production --message "fix"' to publish. Configure updates URL and runtime version in app.json. Updates download on next app launch and apply automatically.
By default screens stay mounted in the navigation stack, so state persists when navigating away and back. Use the useFocusEffect hook or unmountOnBlur/freezesOnBlur options to control when effects run and when components unmount.
React Native Mobile
What is a FlashList and why is it faster than FlatList?
Modal is a core component that presents content above the enclosing view, blocking interaction with the rest of the app. Use the visible prop to control display, animationType for slide/fade transitions, and transparent for overlays.
Pass a function to style prop instead of an object: style={({pressed}) => [styles.base, pressed && styles.pressed]}. The function receives pressed, hovered (web), and focused states, enabling per-state visual feedback declaratively.
FlashList (from @shopify/flash-list) recycles native views like RecyclerView/UICollectionView instead of unmounting off-screen items. It dramatically improves performance for large lists, with simpler props than FlatList and built-in recycling.
SectionList renders a list of sectioned data, similar to FlatList but with grouped sections each having a header. You provide sections array (with data and title), renderItem for items, renderSectionHeader for headers, and keyExtractor for unique keys.
React Native Mobile
What is the purpose of the useLayoutEffect hook?
Use expo-local-authentication's authenticateAsync() with BiometricSecurityLevel options, or react-native-biometrics' simplePrompt(). Wrap the call in a try/catch handling userCancel and authenticationError codes gracefully.
useLayoutEffect fires synchronously after DOM mutations but before the browser paints, allowing you to read layout and re-render immediately. In React Native it's similar to useEffect but blocks paint; use it sparingly for measuring views.
Pass a linking prop to NavigationContainer with prefixes: ['myapp://'], then config mapping screens to paths: { screens: { Home: '', Profile: 'user/:id' } }. React Navigation parses incoming URLs and dispatches matching routes.
It applies 2D or 3D transformations to a component, such as `translateX`, `translateY`, `scale`, `rotate`, and `perspective`. Transformations are applied after layout, so they do not affect the surrounding layout of sibling components.
React Native Mobile
How do you run a React Native app on an iOS simulator using the CLI?
SectionList renders a list of sectioned data, similar to FlatList but with grouped sections each having a header. You provide sections array (with data and title), renderItem for items, renderSectionHeader for headers, and keyExtractor for unique keys.
Declare a RootStackParamList type mapping route names to their param shapes, then use createNativeStackNavigator(). Access params via route.params with proper typing, ensuring type safety across navigation calls.
useMemo memoizes a computed value, recomputing only when dependencies change: const result = useMemo(() => compute(a, b), [a, b]). useCallback memoizes a function itself: const fn = useCallback(() => doSomething(a), [a]). useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).
With a Mac and Xcode installed, run 'npx react-native run-ios' from the project root. Optionally pass --simulator='iPhone 15' to target a specific device. Metro bundler must be running, started via 'npx react-native start'.
React Native Mobile
What is the difference between useEffect and useLayoutEffect timing?
EAS Build is Expo's cloud build service that compiles your app on Expo servers for iOS and Android, handling signing credentials automatically. Local builds require Xcode/Android Studio and manual signing setup but don't need network uploads.
Use react-native-safe-area-context library: wrap app in SafeAreaProvider, then use useSafeAreaInsets() hook or component. This handles notches, home indicators, and dynamic insets on orientation change.
useEffect runs asynchronously after paint, allowing browser/native to potentially flicker. useLayoutEffect runs synchronously after DOM/view mutations but before paint, ideal for measuring layout, setting scroll position, or preventing visual flicker.
useContext accesses values from a React context without nesting Consumer components. Wrap the app in and read with const value = useContext(MyContext). It eliminates prop drilling for themes, auth state, or locale settings across the component tree.
React Native Mobile
How do you implement pull-to-refresh in a FlatList?
EAS is a suite of hosted services from Expo for building and submitting React Native apps. EAS Build compiles apps in the cloud for iOS and Android, EAS Submit uploads them to stores, and EAS Update delivers over-the-air JavaScript updates without store review.
Set the refreshing state with useState, define an onRefresh async handler that fetches data and updates state, and pass both to FlatList: . Optionally set colors or tintColor for the spinner.
Combine onEndReached, onEndReachedThreshold (fraction of list length, e.g., 0.5), and a loading state. When the user nears the end, call onEndReached to fetch more data and append it to the existing data array, showing a spinner via ListFooterComponent.
It returns the device pixel density multiplier (e.g., 2 on standard retina, 3 on iPhone Plus). Use it to scale dimensions: `const size = 16 * PixelRatio.getFontScale()` keeps text consistent across devices, and to pick appropriate image resolutions.
React Native Mobile
What does the `useNavigation` hook return in React Navigation?
Run 'npm install -g expo-cli' for the classic CLI or 'npm install -g eas-cli' for the modern Expo Application Services CLI used for builds and submissions. Node 18+ is recommended.
It returns the navigation prop object for the current screen, allowing you to call methods like `navigate('ScreenName', params)`, `goBack()`, `setOptions()`, `addListener`, and `dispatch` without explicitly passing navigation down through props.
It provides a textual label for screen readers, used by assistive technologies like VoiceOver on iOS and TalkBack on Android. When the element receives accessibility focus, the label is read aloud, improving usability for visually impaired users.
Use react-native-safe-area-context library: wrap app in SafeAreaProvider, then use useSafeAreaInsets() hook or component. This handles notches, home indicators, and dynamic insets on orientation change.
React Native Mobile
What is the role of the new architecture (Fabric/TurboModules) in React Native?
Run 'npx react-native bundle --platform ios --dev false --entry-file index.js --bundle-output ios/main.jsbundle --assets-dest ios' to generate the JS bundle. iOS also requires updating AppDelegate to load from bundle in release mode.
Pass a function to style prop instead of an object: style={({pressed}) => [styles.base, pressed && styles.pressed]}. The function receives pressed, hovered (web), and focused states, enabling per-state visual feedback declaratively.
Fabric is the new rendering system using synchronous JSI calls for layout and shadow tree updates. TurboModules enable lazy-loaded native modules with type-safe JSI specs. Together they improve startup time, memory use, and concurrent rendering.
useMemo memoizes a computed value, recomputing only when dependencies change: const result = useMemo(() => compute(a, b), [a, b]). useCallback memoizes a function itself: const fn = useCallback(() => doSomething(a), [a]). useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).
React Native Mobile
What is the difference between React Native CLI and Expo CLI?
Metro, the default JavaScript bundler for React Native, runs on port 8081 by default. The native app connects to this port in development mode to download the JavaScript bundle from your local machine.
Use the BackHandler API with BackHandler.addEventListener('hardwareBackPress', callback). The callback returns true to prevent default behavior. In React Navigation, screen options like headerBackTitle, gestureEnabled, and the useFocusEffect hook manage back behavior.
React Native CLI gives full native control but requires Xcode/Android Studio setup and native dependency management. Expo CLI offers managed workflow with easier setup and OTA updates, historically limiting native modules (now mitigated by Expo Dev Clients and prebuild).
It exposes app constants such as `expoConfig`, `appOwnership` (expo/standalone/bare), `platform`, `deviceName`, and environment-specific values. This is useful for conditionally running code based on whether the app is in Expo Go, a dev build, or a production build.
React Native Mobile
What is the purpose of the StyleSheet.create method in React Native?
The expo-location module provides APIs to read the current GPS position, watch position changes, request foreground/background permissions, and geocode addresses. Always request permissions before accessing coordinates.
Platform.OS returns 'ios' or 'android', letting you write platform-specific code. Use Platform.select({ios: {...}, android: {...}}) for styles or conditionally import components. You can also use Platform.Version to check OS version numbers for compatibility.
Managed workflow uses Expo Go and config plugins, with no native code access. Bare workflow generates ios/android directories for custom native modules. Prebuild command can convert between them, with EAS Build supporting both.
It creates a frozen style object from a JavaScript object. This validates styles, prevents accidental mutation, and improves performance by allowing the styles to be sent across the native bridge only once and referenced by ID, rather than passing the entire style object on every render.
React Native Mobile
How do you add a vector icon to a React Native project?
Install react-native-vector-icons, link fonts in Info.plist (iOS) and android/app/build.gradle (Android), then import: import Icon from 'react-native-vector-icons/MaterialIcons'; . Expo projects use @expo/vector-icons built in with the Expo SDK.
`Alert.alert` uses the native platform alert dialog, requires minimal code, and blocks UI flow until dismissed. A custom `Modal` is rendered with React components, is fully styleable, can contain complex layouts, and supports animations and custom buttons.
It exposes app constants such as `expoConfig`, `appOwnership` (expo/standalone/bare), `platform`, `deviceName`, and environment-specific values. This is useful for conditionally running code based on whether the app is in Expo Go, a dev build, or a production build.
Apply style={{flex: 1}} or alignSelf: 'stretch' to the Text component. Without these, Text only wraps its content. flex: 1 grows the component to fill remaining space along the main axis.
React Native Mobile
How do you add a splash screen to an Expo project?
Run cd android && ./gradlew assembleRelease. The unsigned APK appears in android/app/build/outputs/apk/release/. For a signed AAB, configure signingConfigs in android/app/build.gradle and run ./gradlew bundleRelease, outputting to build/outputs/bundle/release.
AppState tells you whether the app is in the foreground, background, or inactive. Use AppState.addEventListener('change', handler) to detect transitions. This is useful for pausing video playback, stopping location tracking, or managing push notification badges when the app backgrounds.
Import the component and use react-test-renderer or @testing-library/react-native. Example: test('renders correctly', () => { const tree = render().toJSON(); expect(tree).toMatchSnapshot(); }). Mock native modules in jest.setup.js.
Install expo-splash-screen, call SplashScreen.preventAutoHideAsync() in App.js, then SplashScreen.hideAsync() once resources load. Customize background color, image, and resizeMode via app.json's splash plugin configuration.
React Native Mobile
How do you detect network connectivity changes in React Native?
Use expo-local-authentication's authenticateAsync() with BiometricSecurityLevel options, or react-native-biometrics' simplePrompt(). Wrap the call in a try/catch handling userCancel and authenticationError codes gracefully.
EAS Build is a hosted cloud service that compiles your managed or bare React Native project into signed iOS IPA and Android AAB/APK files in the cloud, eliminating the need for local Xcode or Android Studio build setups.
Use @react-native-community/netinfo library. Import NetInfo and call NetInfo.addEventListener(state => { console.log('Is connected?', state.isConnected); }). It provides real-time updates and access to connection type (wifi, cellular, none).
AppState tells you whether the app is in the foreground, background, or inactive. Use AppState.addEventListener('change', handler) to detect transitions. This is useful for pausing video playback, stopping location tracking, or managing push notification badges when the app backgrounds.
React Native Mobile
What is the Pressable component's hitRect prop used for?
Install the package, link fonts: iOS adds UIAppFonts entries in Info.plist with font file names; Android copies .ttf files to android/app/src/main/assets/fonts. Then import Icon from 'react-native-vector-icons/MaterialIcons' to render .
Add accessibilityLabel='Descriptive name' for screen readers, accessibilityHint='What activating does' for action context, and accessibilityRole='button' to communicate element type. Group related elements with accessibilityElementsHidden for cleaner navigation.
hitRect extends or reduces the touchable area of a Pressable beyond its visual bounds. It takes an object with top, bottom, left, right numeric values, allowing you to make small UI elements easier to tap without enlarging their visual footprint.
Use XMLHttpRequest or the fetch API with a Blob. For progress, use the onUploadProgress callback in axios. Alternatively, libraries like react-native-background-upload or Expo's FileSystem.uploadAsync handle uploads with progress events, supporting background continuation.
React Native Mobile
How do you navigate to a screen with parameters in React Navigation?
The default flexDirection is 'column' in React Native, which differs from the web's default of 'row'. Children stack vertically from top to bottom unless you change flexDirection to 'row', 'row-reverse', or 'column-reverse'.
Hot Reloading was the legacy mechanism that injected updated modules while preserving state but had bugs with hooks. Fast Refresh is the modern replacement that reliably preserves component state across edits, supports function components and hooks, and falls back to full reload when state preservation is impossible.
Call navigation.navigate('RouteName', { itemId: 86, otherParam: 'anything' }). The receiving screen accesses parameters via the route prop: const { itemId } = route.params; In TypeScript, declare the param list in the navigator's generic type.
Import { Alert } from 'react-native' and call Alert.alert(title, message, [{text:'OK', onPress: ...}]). On iOS it uses the native UIAlertController; on Android it uses the native AlertDialog via a single button on Android.
React Native Mobile
How do you create a controlled text input in React Native?
Pass a linking prop to NavigationContainer with prefixes: ['myapp://'], then config mapping screens to paths: { screens: { Home: '', Profile: 'user/:id' } }. React Navigation parses incoming URLs and dispatches matching routes.
Use the TextInput component with its value prop bound to component state and onChangeText handler updating that state: const [text, setText] = useState(''); . The component fully controls the input value.
AppState tells you whether the app is in 'active', 'background', or 'inactive' (iOS only) state. Subscribe with AppState.addEventListener('change', handler) to pause/resume animations, save data when backgrounded, or refresh content when foregrounded.
Store keys in environment variables via process.env.API_KEY, set in .env files at build time. For runtime, use a secure backend proxy that holds secrets server-side. Never hardcode keys in JavaScript bundles—APK/IPA extraction is trivial. Use react-native-config or expo-constants for build-time injection.
React Native Mobile
What is the default port for the Metro bundler in React Native?
Metro, the default JavaScript bundler for React Native, runs on port 8081 by default. The native app connects to this port in development mode to download the JavaScript bundle from your local machine.
It exposes app constants such as `expoConfig`, `appOwnership` (expo/standalone/bare), `platform`, `deviceName`, and environment-specific values. This is useful for conditionally running code based on whether the app is in Expo Go, a dev build, or a production build.
useReducer manages complex local state with multiple sub-values or when the next state depends on the previous one. It accepts (state, action) => newState and returns the current state plus a dispatch function, similar to Redux's pattern.
Edit android/app/gradle.properties and set hermesEnabled=true. In ios/Podfile, set :hermes_enabled => true. Then run pod install for iOS and rebuild. Hermes is enabled by default in newer React Native versions.
React Native Mobile
What does the useEffect cleanup function do and when does it run?
Call navigation.navigate('RouteName', { itemId: 86, otherParam: 'anything' }). The receiving screen accesses parameters via the route prop: const { itemId } = route.params; In TypeScript, declare the param list in the navigator's generic type.
It exposes app constants such as `expoConfig`, `appOwnership` (expo/standalone/bare), `platform`, `deviceName`, and environment-specific values. This is useful for conditionally running code based on whether the app is in Expo Go, a dev build, or a production build.
The cleanup function returned from useEffect runs before the component unmounts and before the effect re-runs (if dependencies change). It's used to unsubscribe from listeners, cancel timers, or abort network requests to prevent memory leaks.
Use the TextInput component with its value prop bound to component state and onChangeText handler updating that state: const [text, setText] = useState(''); . The component fully controls the input value.
React Native Mobile
What does `Linking.openURL` do in React Native?
Hermes is a JavaScript engine optimized for React Native, enabling faster app startup, reduced memory usage, and smaller app size. It precompiles JavaScript to bytecode and is enabled by default in modern React Native projects.
Use the useFocusEffect hook with a useCallback that calls React.useEffect internally. This runs the effect every time the screen comes into focus, ensuring imperative actions like fetching data or starting animations run when needed.
It opens a URL in the appropriate native application, such as launching a web browser, opening the phone dialer with a `tel:` link, composing an email with a `mailto:` link, or navigating to another app via a custom URL scheme.
Use the useColorScheme hook (added in RN 0.65) which returns 'light', 'dark', or null. Define theme objects with color palettes and apply them conditionally: const theme = useColorScheme() === 'dark' ? darkTheme : lightTheme. Persist user override via AsyncStorage.