React Native interview questions and answers for 2025
React Native Interview Questions for Freshers and Intermediate Levels
What is React Native, and how does it differ from React?
React Native is an open-source framework developed by Facebook for building mobile applications using JavaScript and React. It allows developers to create natively rendered apps for iOS and Android using a single codebase.
The key differences between React and React Native are:
- Platform: React is used for building web applications, while React Native is used for mobile app development.“
- Rendering: React uses HTML and CSS for rendering UI components, whereas React Native uses native components specific to the mobile platform.
- Styling: React Native uses
StyleSheet
objects and styles that resemble CSS but are not exactly the same.
Explain the concept of “props” and “state” in React Native.
- Props (Properties): Props are read-only inputs passed to a component from its parent. They are immutable and used to pass data and configuration down the component tree.
const Greeting = (props) => {
return Hello, {props.name}!;
};
- State: State represents mutable data that can change over time within a component. It is managed within the component and can be updated using the setState method or React Hooks like useState.
const Counter = () => {
const [count, setCount] = useState(0);
return (
<View>
<Text>{count}</Text>
<Button onPress={() => setCount(count + 1)} title="Increment" />
</View>
);
};
How do you handle styling in React Native?
Styling in React Native is done using JavaScript objects, similar to CSS but not identical. Styles are created using the StyleSheet
API.
import { StyleSheet, Text, View } from 'react-native';
const styles = StyleSheet.create({
container: {
backgroundColor: 'blue',
padding: 10,
},
text: {
color: 'white',
fontSize: 18,
},
});
const App = () => (
Hello World
);
What is the purpose of the key prop in lists?
The key
prop helps React identify which items have changed, are added, or are removed. Keys should be unique and stable identifiers, and they optimize rendering performance by allowing React to minimize DOM manipulations.
const items = data.map((item) => {item.name});
Explain the use of Flexbox in React Native. And what is default flex direction in react-native?
React Native uses Flexbox for layout, allowing for responsive design across different screen sizes. Flexbox properties like flexDirection
, justifyContent
, and alignItems
are used to align and distribute space among items. Default direction is column.
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row', // row or column
justifyContent: 'center', // align horizontally
alignItems: 'center', // align vertically
},
});
How do you make API calls in React Native?
API calls can be made using JavaScript’s fetch
API or third-party libraries like axios
.
useEffect(() => {
fetch('https://api.example.com/data')
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error));
}, []);
What is the difference between ScrollView and FlatList?
- ScrollView: Renders all its child components at once, which may affect performance with large data sets.
- FlatList: Efficiently renders a list of items using lazy loading and only renders items that are currently visible on the screen.
How do you navigate between screens in React Native?
Navigation between screens is commonly handled using libraries like React Navigation
.
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
const App = () => (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
Explain the concept of “Virtual DOM” in React Native.
React Native uses a Virtual DOM to optimize UI rendering. When the state of a component changes, React calculates the difference between the previous and current Virtual DOM and updates only the necessary parts of the UI, improving performance.
What are Higher-Order Components (HOC) in React Native?
An HOC is a function that takes a component and returns a new component, enhancing it with additional functionality.
const withLogger = (WrappedComponent) => {
return class extends React.Component {
componentDidMount() {
console.log('Component Mounted');
}
render() {
return ;
}
};
};
How do you manage state in a large React Native application?
State management can be handled using:
- Context API: For passing data through the component tree without props.
- Redux: A predictable state container for managing application state.
- MobX: For simple and scalable state management.
What is the purpose of useEffect hook?
The useEffect
hook allows you to perform side effects in function components, replacing lifecycle methods like componentDidMount
, componentDidUpdate
, and componentWillUnmount
.
useEffect(() => {
// Effect logic
return () => {
// Cleanup
};
}, [dependencies]);
Explain how to handle forms and user input in React Native.
Forms can be handled using TextInput
components and state to manage the input values.
const [text, setText] = useState('');
setText(val)}
placeholder="Enter text"
/>;
What is the difference between React.Component and
React.PureComponent?
The distinction between React.Component
and React.PureComponent
lies in their update behavior and performance optimizations:optimizations:
React.Component
- Base Implementation: Requires manual control over re-renders.
shouldComponentUpdate
: Not implemented by default. The component re-renders every time its state or props change, regardless of whether the data is actually different.- Use Case: Ideal when you need full control over updates, such as handling deeply nested data or mutable state where shallow comparisons are insufficient.
React.PureComponent
- Automatic Optimization: Implements
shouldComponentUpdate
with a shallow comparison of props and state.- Shallow Comparison: Checks if top-level property values (for primitives) or
references (for objects/arrays) have changed. If no differences are detected, the component skips re-rendering.
- Shallow Comparison: Checks if top-level property values (for primitives) or
- Performance Benefit: Reduces unnecessary re-renders when props/state are immutable and changes are detectable via reference checks.
- Caveats:
- Immutable Data Required: Mutating nested objects/arrays directly won’t trigger re-renders, as references remain unchanged.
- Not for Deep Changes: Inefficient for props/state with deeply nested structures that change frequently without reference updates.
- Use Case: Best for components with simple props/state or when performance gains from avoiding redundant renders outweigh potential pitfalls.
How do you debug a React Native application?
Debugging can be done using:
- Console Logs: Using
console.log()
statements. - React Native Debugger: A standalone app for debugging.
- Remote Debugging: Via Chrome Developer Tools.
- Flipper: A mobile app debugging tool.
What is the role of ref in React Native?
ref
provides a way to access DOM nodes or React elements directly.
const inputRef = useRef(null);
;
const focusInput = () => {
inputRef.current.focus();
};
How do you handle platform-specific code in React Native?
Platform-specific code can be handled using:
- Platform Module: Using
Platform.OS
to conditionally render components. - File Extensions: Naming files as
Component.android.js
orComponent.ios.js
.
What are controlled and uncontrolled components?
- Controlled Components: Components where the form data is handled by React state.
- Uncontrolled Components: Components where form data is handled by the DOM itself.
In React Native, it’s common to use controlled components for better control over the data.
Explain the importance of keys in FlatList items.
Keys help FlatList optimize rendering by tracking items, ensuring that only items that have changed are re-rendered.
{item.name}}
keyExtractor={(item) => item.id.toString()}
/>
What is the purpose of AsyncStorage in React Native? Do you use any other storage library that is synchronous and faster, such as MMKV?
AsyncStorage
is a simple, asynchronous, unencrypted key-value storage system for persisting data in React Native applications. It allows storing small amounts of data persistently on the device.
Example usage:
import AsyncStorage from '@react-native-async-storage/async-storage';
const storeData = async (value) => {
try {
await AsyncStorage.setItem('@storage_Key', value);
} catch (e) {
console.error('Saving error', e);
}
};
Limitations of AsyncStorage
- Performance: It is asynchronous but not optimized for large-scale data storage, as it uses JSON serialization.
- Speed: Slower compared to native storage options since it operates on a JavaScript bridge.
- Encryption: It does not provide built-in encryption, making it less secure for sensitive data.
Alternative: MMKV
For better performance, react-native-mmkv is a great alternative. MMKV is a high-performance, synchronous storage solution that operates much faster than
AsyncStorage
.
Example usage with MMKV:
import { MMKV } from 'react-native-mmkv';
const storage = new MMKV();
storage.set('storage_Key', 'some_value');
When to use AsyncStorage
vs. MMKV
- Use
AsyncStorage
for simple key-value storage when performance isn’t critical. - Use
MMKV
for faster, synchronous operations and better performance.
How do you handle gestures in React Native?
Gestures in React Native can be handled using various approaches:
- Touchable Components:
TouchableOpacity
,TouchableHighlight
, and
Pressable
.Pressable
is a Core Component wrapper that detects multiple stages of a press interaction, making it more flexible than traditionalTouchable
components.
- Gesture Responder System: A low-level API for handling touch interactions manually.
- Libraries:
react-native-gesture-handler
– Recommended for handling complex gestures with better performance and native-like behavior.react-native-reanimated
– Often used in combination with
react-native-gesture-handler
for smooth animations and gesture-based interactions.
Explain the use of Modal component.
The Modal
component is used to create overlay dialogs or pop-ups.
setModalVisible(false)}
>
{/* Modal Content */}
How do you optimize performance in React Native applications?
- Use PureComponent or React.memo
- Avoid anonymous functions in render
- Optimize rendering lists with FlatList
- Use shouldComponentUpdate or React.memo
- Minimize re-renders by proper state management
Explain how to handle screen orientation changes.
Screen orientation can be handled using the Dimensions
API or the
react-native-orientation-locker
library.
import { Dimensions } from 'react-native';
const { width, height } = Dimensions.get('window');
What is Props Drilling and How Can You Avoid It?
Props drilling is the process of passing props through multiple levels of nested components to reach a deeply nested child. This can lead to unnecessary complexity and tightly coupled components.
To avoid props drilling, you can use:
- Context API: Provides a way to pass data through the component tree without manually passing props at every level.
- State Management Libraries: Such as Redux or MobX, which manage state globally and prevent excessive prop passing.
- Composition: Instead of deeply nesting components, you can use composition to structure your components in a way that reduces the need for props drilling. This approach focuses on creating reusable, flexible components that receive data and behavior as props, enhancing modularity.
How do you handle errors in React Native?
Errors in React Native can be handled using various techniques:
- Try-Catch Blocks: Used for handling errors in synchronous code.
try {
// Some operation
} catch (error) {
console.error('Error:', error);
}
- Promise .catch() Blocks: Used for handling errors in asynchronous operations.
fetch('https://api.example.com/data')
.then((response) => response.json())
.catch((error) => console.error('Fetch error:', error));
- React Error Boundaries:While functional components are widely used in React Native, Error Boundaries are still implemented using class components. They catch JavaScript errors in the component tree and prevent the app from crashing.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error('Error boundary caught an error:', error, info);
}
render() {
if (this.state.hasError) {
return Something went wrong.;
}
return this.props.children;
}
}
- Custom Hooks for Error Handling:Since React Native is functionally oriented, a common pattern is to use custom hooks for error handling.
import { useState } from 'react';
const useErrorHandler = () => {
const [error, setError] = useState(null);
const handleError = (err) => {
console.error(err);
setError(err);
};
return { error, handleError };
};
This allows handling errors in functional components more effectively.
What is React Native CLI, and how does it differ from Expo? What is recommended currently to start your new rn project?
React Native apps can be built using two primary approaches:
- React Native CLI:
- Offers full control over the build process.
- Allows direct integration with native modules and custom native code.
- Requires setting up Xcode (for iOS) and Android Studio (for Android).
- More complex setup but ideal for projects needing deep native customizations.
- Expo:
- A framework and platform for developing React Native apps with an easier setup.
- Provides a managed workflow, allowing developers to build apps without configuring native dependencies manually.
- Includes a wide range of pre-built APIs but may have limitations when integrating custom native modules.
- Supports EAS (Expo Application Services) for building, deploying, and updating apps more efficiently.
Which one to choose?
- Expo is recommended for most new projects due to its streamlined workflow and ease of development.
- React Native CLI is better suited for apps requiring extensive native module integration or deep platform-specific customizations.
React native in their official documentation recommend expo as way to build mobile apps using react native.
React Native Interview Questions for Experienced Levels
Explain the architecture of React Native and how it works.
Legacy Architecture (Pre-0.68)
Core Components
- JavaScript Thread
- Executes React logic, handles business rules, and manages component state.
- Uses JavaScriptCore (JSC) or Hermes engine.
- Native (UI) Thread
- Renders platform-specific UI components (e.g., Android
View
, iOSUIView
). - Handles user interactions (e.g., touch events).
- Renders platform-specific UI components (e.g., Android
- Shadow Thread
- Computes layout using Yoga (converts React flexbox rules to native layout).
- Bridge
- Asynchronous communication layer between JavaScript and native threads.
- Serializes messages to JSON for cross-thread transfer.
Workflow
- UI Update Example:
- JavaScript sends a layout update (e.g.,
setState
) → Serialized to JSON → Bridge → Native thread → Yoga computes layout → UI renders.
- JavaScript sends a layout update (e.g.,
- Event Handling Example:
- User taps a button → Native thread → Serialized event → Bridge → JavaScript thread → Handler executes.
Limitations
- Performance Bottlenecks: JSON serialization and asynchronous messaging caused delays.
- UI Jank: Layout recalculations on the shadow thread led to flickering.
- No Direct Native Access: JavaScript couldn’t reference native objects directly.
New Architecture (0.68+)
Core Components
- JavaScript Interface (JSI)
- Replaces the bridge with a C++ layer for direct, synchronous communication.
- JavaScript can hold references to native objects (no serialization).
- TurboModules
- Lazily loaded native modules (e.g., Camera, Bluetooth).
- Codegen auto-generates type-safe interfaces (TypeScript ↔ Native).
- Fabric Renderer
- Thread-safe, concurrent UI renderer written in C++.
- Maintains an immutable UI tree for efficient updates.
- Concurrent React
- Supports React 18 features like Suspense, Transitions, and batched updates.
Workflow
- UI Update Example:
- JavaScript updates state → Fabric synchronously updates the UI tree → Native thread renders without serialization.
- Event Handling Example:
- User interaction → Direct callback to JavaScript via JSI (no bridge delays).
Benefits
- Faster Execution: No JSON serialization or async bottlenecks.
- Synchronous Layout:
useLayoutEffect
measures UI changes in one pass. - Type Safety: Codegen ensures props/API consistency between platforms.
- Lazy Loading: TurboModules reduce startup time.
Comparison Table
Feature | Legacy Architecture | New Architecture |
Communication | Async JSON Bridge | Direct sync via JSI |
Native Modules | Eagerly loaded (
|
Lazily loaded TurboModules |
UI Rendering | Single-threaded, mutable tree | Concurrent, immutable Fabric tree |
Layout Calculation | Async (Shadow Thread) | Sync (Multi-threaded) |
Performance | Slower (serialization overhead) | Faster (no serialization) |
React 18+ Support | Limited | Full (Suspense, Transitions, etc.) |
How do you implement code splitting and lazy loading in React Native?
Code splitting and lazy loading can be achieved using dynamic import()
statements and React’s Suspense
component.
const LazyComponent = React.lazy(() => import('./LazyComponent'));
const App = () => (
}>
);
What are Hooks, and how do they change the way we write React Native components?
Hooks are functions that let you use state and other React features without writing a class. They simplify the codebase and make it easier to share logic between components.
- useState: For state management.
- useEffect: For side effects.
- useContext: For consuming context.
Discuss the process of integrating native modules in React Native.
Native modules enable React Native apps to access platform-specific APIs (e.g., hardware sensors, OS services). The integration process differs between the legacy bridge-based architecture and the new TurboModule/JSI architecture:
1. Legacy Architecture (Bridge-Based)
- Process:
- Native Module Creation:
- Define platform-specific logic in native languages (Java/Kotlin for Android, Objective-C/Swift for iOS).
- Bridge Communication:
- Expose methods to JavaScript using React Native’s bridge, which serializes data into JSON for asynchronous message passing.
- Module Registration:
- Register the module in platform-specific code to make it accessible in JavaScript.
- Native Module Creation:
- Limitations:
- Performance Overhead: JSON serialization and asynchronous communication introduce delays.
- Boilerplate: Manual setup for method binding and type conversions.
- Eager Loading: Modules initialize at app startup, increasing load time.
2. New Architecture (TurboModules + JSI)
- Process:
- TypeScript Interface Definition:
- Declare the module’s API in a TypeScript spec file, enforcing type safety.
- Code Generation:
- Use Codegen to auto-generate native platform code (Java/Kotlin, Objective-C/Swift) and JavaScript interfaces.
- Direct Communication (JSI):
- Replace the bridge with the JavaScript Interface (JSI), enabling synchronous method calls and direct access to native objects.
- Lazy Loading:
- Modules load only when needed, reducing startup time.
- TypeScript Interface Definition:
- Advantages:
- Improved Performance: No serialization or asynchronous bottlenecks.
- Type Safety: Auto-generated interfaces reduce runtime errors.
- Simplified Maintenance: Codegen eliminates manual boilerplate.
Key Differences
Aspect | Legacy (Bridge) | New (TurboModules) |
Communication | Async via JSON bridge | Direct sync via JSI |
Type Handling | Manual type conversions | Enforced by Codegen |
Module Loading | Loaded at app startup | Loaded on-demand |
Performance | Slower (serialization overhead) | Faster (direct access) |
When to Use Native Modules
- Access platform-specific APIs (e.g., Bluetooth, camera).
- Optimize performance-critical tasks (e.g., image processing).
- Reuse existing native libraries.
Migration to the New Architecture
- Adopt Codegen: Define TypeScript specs to auto-generate native code.
- Refactor Modules: Convert bridge-based modules to TurboModules.
- Enable JSI: Configure the app to use the new architecture.
How do you handle performance optimization for animations in React Native?
Modern animation optimization leverages React Native Reanimated, Gesture Handler, and platform-specific optimizations to achieve 60 FPS performance.
1. Use React Native Reanimated
- Why: Reanimated runs animations on the UI thread (not the JavaScript thread), eliminating bridge overhead and jank.
- Key Features:
- Worklets: Write JavaScript logic that executes synchronously on the UI thread (e.g., gesture-driven animations).
- Shared Element Transitions: Smooth transitions between screens (supported in Reanimated 3+).
- Layout Animations: Animate layout changes (e.g.,
flexbox
adjustments) with
withTiming
orwithSpring
. - Declarative API: Define animations in a React-like style.
- Native Performance: No serialization via the bridge (uses JSI in the new architecture).
2. Replace Animated
with Reanimated
- Legacy Approach:
useNativeDriver: true
offloads simple animations (e.g., opacity, transform) to the native thread.- Limited to a subset of properties and no interaction with gestures.
- Modern Approach:
- Reanimated handles complex animations (e.g., interpolations, gesture-based) entirely on the UI thread.
- Example: Follow a finger drag with
useAnimatedGestureHandler
+
useSharedValue
.
3. Optimize Gestures with Gesture Handler
- React Native Gesture Handler:
- Processes touch events on the native thread, avoiding JS thread congestion.
- Enables simultaneous gestures (e.g., pinch + rotate) and interruptible animations.
- Integrates seamlessly with Reanimated for buttery-smooth interactions.
4. Avoid JavaScript Thread Work
- Offload Calculations:
- Use Reanimated’s
runOnJS
for non-UI logic (e.g., API calls) to keep animations on the UI thread. - Memoization: Cache expensive computations with
useMemo
oruseCallback
.
- Use Reanimated’s
- Reduce Re-renders:
- Use
React.memo
for components involved in animations. - Avoid state updates during active animations.
- Use
5. Optimize for the New Architecture
- Fabric Renderer:
- Reduces UI thread load with concurrent rendering and immutable shadow trees.
- TurboModules:
- Faster native module access for animation-related APIs (e.g., sensors).
6. Platform-Specific Techniques
- Android:
- Enable
hardwareAccelerated
inAndroidManifest.xml
. - Use
FLAG_LAYOUT_NO_LIMITS
for full-screen animations.
- Enable
- iOS:
- Prefer
Core Animation
for static transitions (e.g.,UIManager
’sanimate
).
- Prefer
7. Tools for Debugging
- Reanimated DevTools: Inspect animation values and gesture states.
- Flipper: Profile JS/Native thread performance and identify drops below 60 FPS.
- React Native Profiler: Track re-renders and JS thread bottlenecks.
8. Additional Tips
- Reuse Animated Nodes: Cache
Animated.Value
orSharedValue
instances. - Simplify Animations: Avoid nested interpolations; use
Easing
presets. - Use Platform Drivers: For Lottie, enable
hardwareAcceleration
on Android. - Lazy Load Animations: Load heavy animations only when needed.
When to Use Which Library
Scenario | Tool |
Simple transforms/opacity | Animated + useNativeDriver |
Gesture-driven animations | Reanimated + Gesture Handler |
Complex UI transitions | Reanimated’s Layout Animations |
SVG/vector animations | Lottie or React Native Skia or Rive |
For modern apps, Reanimated 3 is the gold standard for animations. Pair it with Gesture Handler and the new architecture (Fabric/JSI) to achieve native-like performance. Migrate legacy Animated
code to Reanimated for complex use cases.
What are Context Providers, and how do you use them?
Context Providers allow you to pass data through the component tree without manually passing props at every level.
const ThemeContext = React.createContext('light');
const App = () => (
);
How do you manage side effects in a React Native application?
Side effects are managed using:
- useEffect Hook: For functional components.
- Lifecycle Methods: For class components.
- Middleware: In state management libraries like Redux Thunk or Redux Saga.
How do you handle deep linking in React Native?
Deep linking can be implemented using:
- Linking API: React Native’s built-in module for handling links.
- React Navigation: Configuring navigation to respond to specific URL patterns.
Linking.addEventListener('url', (event) => {
navigate(event.url);
});
Explain the importance of memoization in React Native and how to implement it.
Memoization prevents unnecessary re-renders by caching results of expensive function calls.
- React.memo: Higher-order component for functional components.
- useMemo Hook: Memoizes values.
- useCallback Hook: Memoizes functions.
How do you secure a React Native application?
- Secure Storage: Use encrypted storage for sensitive data.
- Network Security: Use HTTPS and validate SSL certificates.
- Code Obfuscation: Minify and obfuscate code to prevent reverse engineering.
- Input Validation: Sanitize user input to prevent injection attacks.
Discuss the pros and cons of using TypeScript with React Native.
Pros:
- Type Safety: Catches errors at compile time.
- Better IDE Support: Improved code completion and navigation.
- Self-documenting Code: Types act as documentation.
Cons:
- Learning Curve: Requires understanding of TypeScript.
- Setup Complexity: Additional configuration needed.
- Compile Overhead: Transpilation step adds complexity.
What is the role of WebSockets in React Native, and how do you implement them?
WebSockets enable real-time, bidirectional communication between the client and server.
const ws = new WebSocket('ws://example.com/socket');
ws.onopen = () => {
ws.send('Hello Server');
};
ws.onmessage = (e) => {
console.log(e.data);
};
ws.onerror = (e) => {
console.error(e.message);
};
Real-World Use Cases for WebSockets in a Mobile App:
- Live financial data: For example, a cryptocurrency or stock trading app can use WebSockets to display real-time price updates without the need to refresh the data manually.
- Chat applications: Instant messaging apps use WebSockets to send and receive messages in real-time.
- Live sports scores: Apps that show live updates for sports matches.
- Collaborative apps: Real-time collaboration features in apps like shared whiteboards or document editors.
How do you handle internationalization (i18n) in React Native?
Internationalization can be handled using libraries like react-native-i18n
or
react-intl
.
import I18n from 'react-native-i18n';
I18n.translations = {
en: { welcome: 'Welcome' },
fr: { welcome: 'Bienvenue' },
};
{I18n.t('welcome')};
Explain how to implement push notifications in React Native.
Implementing push notifications involves:
- Registering the device with a push notification service (e.g., Firebase Cloud Messaging).
- Setting up native modules or using libraries like
react-native-push-notification
. - Handling notification events in the app.
What are the challenges of testing React Native applications, and how do you address them?
Challenges:
- Platform Differences: Tests may behave differently on iOS and Android.
- Async Operations: Testing asynchronous code can be complex.
Solutions:
- Use Testing Libraries: Like Jest and Enzyme for unit testing.
- End-to-End Testing: Using tools like Detox or Appium.
- Mocking Modules: To isolate tests.
How do you optimize images in React Native?
- Use Appropriate Formats: Choose the right image format (JPEG, PNG, WebP).
- Resize Images: Serve images at the correct size.
- Caching: Implement image caching.
- *Use
Image.getSize
to manage layout before loading images.
Discuss how to handle memory leaks in React Native.
- Avoid Unmounted Component Updates: Use
isMounted
flags or cleanup functions inuseEffect
. - Remove Listeners: Unsubscribe from events in
componentWillUnmount
or cleanup functions. - Optimize Render Logic: Prevent unnecessary renders.
Prevent leaks by canceling async tasks, timers, and event listeners in useEffect
cleanup functions. Avoid state updates on unmounted components using refs or conditional checks. Use profiling tools (React DevTools, Flipper) to detect lingering subscriptions or orphaned references.
Explain the use of Proguard in React Native.
Proguard is used to minify and obfuscate Android application code, reducing APK size and improving security.
- Enable Proguard: In
build.gradle
by settingminifyEnabled
totrue
. - Configure Rules: Use
proguard-rules.pro
to specify which code to keep.
How do you handle offline functionality in React Native apps?
Handling offline functionality in React Native apps involves using storage solutions, monitoring network status, and implementing data synchronization strategies.
- Local Storage:
AsyncStorage
– A simple key-value storage system for persisting small amounts of data. However, it is an in-memory storage and can slow down the app when handling large datasets. It is not optimized for structured or complex data storage.- Databases like Realm and WatermelonDB – Suitable for managing larger datasets efficiently. These databases offer better performance, support relationships between data, and handle offline-first scenarios more effectively.
- Network Status Monitoring:
- Use
@react-native-community/netinfo
to detect connectivity changes and adjust app behavior accordingly.
- Use
import NetInfo from '@react-native-community/netinfo';
NetInfo.fetch().then((state) => {
console.log('Is connected?', state.isConnected);
});
- Data Synchronization:
- Queue network requests and retry them when the device is back online.
- Use libraries like
redux-offline
or implement background sync mechanisms to ensure data consistency.
Choosing the right storage solution:
- Use
AsyncStorage
only for lightweight data storage (settings, tokens, preferences). - Use Realm or WatermelonDB for handling large amounts of data efficiently with offline-first capabilities.
What is the significance of ESlint and Prettier in a React Native project?
- ESLint: Enforces code quality by identifying problematic patterns.
- Prettier: Automatically formats code for consistency.
They help maintain a clean and readable codebase.
What are the Benefits and Drawbacks of Using Expo?
Benefits:
- Ease of Use: Simplifies setup and development, making it beginner-friendly.
- Managed Workflow: Handles native dependencies, allowing developers to focus on JavaScript and React Native code.
- Over-the-Air (OTA) Updates: Enables instant app updates without requiring an app store submission.
- Cross-Platform Development: Provides a consistent development experience for both iOS and Android.
- Expo Application Services (EAS): Supports cloud builds, deployment, and updates, reducing the need for native development tools.
Drawbacks:
- App Size: Expo apps tend to be larger because they bundle additional libraries to support various features.
- Ejected Workflow Complexity: While Expo supports custom native code, ejecting to a bare workflow requires additional setup and maintenance.
- Some Native Features Require Custom Development: While Expo now supports custom native modules, certain advanced use cases may still require native code modifications.
Is Expo the Right Choice?
- Expo is ideal for projects that prioritize rapid development, cross-platform compatibility, and minimal native configuration.
- If your app requires extensive custom native modules or optimizations, consider using the bare React Native CLI approach.
What are some best practices for structuring a React Native project?
- Organize Files: Separate components, screens, and utilities.
- Use Index Files: For cleaner imports.
- Follow Naming Conventions: Consistent and descriptive names.
- Modularize Code: Reusable components and functions.
How do you handle fonts and icons in React Native?
- Custom Fonts: Add font files to the project and link them.
- Icons: Use libraries like
react-native-vector-icons
for scalable icons.
Discuss how to implement dark mode in a React Native application.
- Detect System Theme: Use
Appearance
API. - Theming: Use context or state to apply different styles.
- StyleSheet Variations: Create separate styles for light and dark modes.
What are some methods for improving the startup time of a React Native app?
General Optimizations (Applicable to Both Architectures)
- Enable Hermes Engine:
- Reduces JS bundle size by up to 50% and speeds up parsing/execution.
- New Architecture: Hermes is required and works seamlessly with JSI.
- Optimize Assets:
- Compress images (WebP/HEIC) and lazy-load non-critical assets.
- Use tools like
react-native-fast-image
for caching.
- Code Splitting:
- Use dynamic imports (
React.lazy
,import()
) to defer loading non-essential screens/modules.
- Use dynamic imports (
- Preload Critical Data:
- Fetch initial data (e.g., user session) in parallel with app startup.
Legacy Architecture-Specific Improvements
- Avoid Bridge Overload:
- Minimize synchronous bridge calls (e.g.,
measure
,UIManager
methods). - Batch native module calls to reduce JSON serialization overhead.
- Minimize synchronous bridge calls (e.g.,
- Inline Requires:
- Delay loading non-critical JS modules until needed (via
metro.config.js
).
- Delay loading non-critical JS modules until needed (via
- Optimize Native Modules:
- Eagerly load essential modules (e.g., networking) but defer others.
New Architecture-Specific Improvements
- TurboModules:
- Lazy-Load Native Modules: Native code loads only when invoked, reducing startup time.
- Type-Safe Codegen: Auto-generates efficient native bindings, eliminating reflection overhead.
- Fabric Renderer:
- Concurrent Rendering: Prioritizes critical UI elements during startup.
- Immutable Shadow Trees: Reduces layout recalculations.
- JSI (JavaScript Interface):
- Direct memory access to native objects (no bridge serialization).
- Faster initialization of native dependencies (e.g., Reanimated, Skia).
- Pre-Build Native Code:
- Use Codegen to pre-generate C++ types for TurboModules/Fabric, avoiding runtime codegen.
Comparison: Old vs. New Architecture
Optimization | Legacy (Bridge) | New (Fabric/JSI) |
Native Modules | Eagerly loaded (slows startup) | Lazily loaded via TurboModules |
Communication | Async JSON bridge (high overhead) | Sync JSI (no serialization) |
Rendering | Single-threaded UI updates | Concurrent rendering with Fabric |
Bundle Parsing | Slower with JSC | Faster with Hermes + JSI integration |
Startup Codegen | N/A | Pre-built C++ types reduce runtime JS |
Critical Steps for New Architecture
- Migrate to TurboModules: Convert critical native modules to use lazy loading.
- Adopt Codegen: Auto-generate type-safe bindings for native code.
- Enable Concurrent Features: Use React 18’s
startTransition
to prioritize urgent UI during startup.
Tools for Profiling
- Flipper: Track JS/Native thread bottlenecks.
- React DevTools: Identify slow renders or unmemoized components.
- Android Studio/Xcode Instruments: Profile native startup time.
Final Take
The New Architecture cuts startup time by ~30-50% via TurboModules (lazy loading), JSI (no bridge), and Fabric (concurrent rendering). Combine this with Hermes, asset optimization, and code splitting for maximum gains. Migrate legacy apps to leverage these improvements.
React Native Coding Interview Questions
Question 1
You are given the following incomplete Counter
component. Complete the code so that when the “Increment” button is pressed, the count displayed increases by 1.
import React from 'react';
import { View, Text, Button } from 'react-native';
const Counter = () => {
// Initialize state here
return (
<View>
<Text>Count: {/* Display the count here */}</Text>
<Button title="Increment" onPress={/* Handle the button press */} />
</View>
);
};
export default Counter;
Answer:
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<View>
<Text>Count: {count}</Text>
<Button title="Increment" onPress={() => setCount(count + 1)} />
</View>
);
};
export default Counter;
Question 2
Write a custom hook useToggle
that manages a boolean state. The hook should return the current value and a function to toggle it.
// Implement useToggle hook here
Answer:
import { useState, useCallback } from 'react';
const useToggle = (initialValue = false) => {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => setValue((v) => !v), []);
return [value, toggle];
};
export default useToggle;
Question 3
You have a list of tasks stored in an array. Create a TodoList
component that displays the tasks and allows users to add new tasks using a TextInput
.
import React from 'react';
import { View, TextInput, Button, FlatList, Text } from 'react-native';
// Implement TodoList component here
Answer:
import React, { useState } from 'react';
import { View, TextInput, Button, FlatList, Text, StyleSheet } from 'react-native';
const TodoList = () => {
const [text, setText] = useState('');
const [tasks, setTasks] = useState([]);
const addTask = () => {
if (text.trim()) {
setTasks([...tasks, { key: Date.now().toString(), text }]);
setText('');
}
};
return (
<View style={styles.container}>
<TextInput
style={styles.input}
value={text}
placeholder="Add a task"
onChangeText={setText}
/>
<Button title="Add Task" onPress={addTask} />
<FlatList
data={tasks}
keyExtractor={(item) => item.key}
renderItem={({ item }) => <Text style={styles.item}>{item.text}</Text>}
/>
</View>
);
};
const styles = StyleSheet.create({
container: { padding: 20 },
input: { borderBottomWidth: 1, marginBottom: 10 },
item: { padding: 10, fontSize: 18 },
});
export default TodoList;
Question 4
Complete the FetchData
component so that it fetches data from an API when the “Load Data” button is pressed and displays the result.
import React from 'react';
import { View, Button, Text } from 'react-native';
const FetchData = () => {
// Initialize state here
const fetchData = () => {
// Fetch data from API
};
return (
{/* Display data here */}
);
};
export default FetchData;
Answer:
import React, { useState, useEffect } from "react";
import {
View,
Button,
Text,
ActivityIndicator,
StyleSheet,
} from "react-native";
const FetchData = () => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const fetchData = async () => {
try {
setLoading(true);
setError(null);
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts/1"
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json = await response.json();
setData(json);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
return (
<View style={styles.container}>
<Button title="Load Data" onPress={fetchData} disabled={loading} />
{loading && <ActivityIndicator size="small" color="#0000ff" />}
{error && <Text style={styles.error}>Error: {error}</Text>}
{data && <Text style={styles.data}>{data.title}</Text>}
</View>
);
};
const styles = StyleSheet.create({
container: { padding: 20 },
error: { color: "red", marginTop: 10 },
data: { marginTop: 10, fontSize: 16 },
});
export default FetchData;
Question 5
Implement a SearchableList
component that filters a list of names based on user input in a TextInput
.
import React from 'react';
import { View, TextInput, FlatList, Text } from 'react-native';
// Sample data
const names = [
{ id: '1', name: 'Alice' },
{ id: '2', name: 'Bob' },
// More names...
];
// Implement SearchableList component here
Answer:
import React, { useState, useMemo } from "react";
import {
View,
TextInput,
FlatList,
Text,
StyleSheet,
Keyboard,
} from "react-native";
const names = [
{ id: "1", name: "Alice" },
{ id: "2", name: "Bob" },
{ id: "3", name: "Charlie" },
{ id: "4", name: "David" },
];
const SearchableList = () => {
const [search, setSearch] = useState("");
const filteredNames = useMemo(
() =>
names.filter((item) =>
item.name.toLowerCase().includes(search.toLowerCase())
),
[search]
);
const renderItem = ({ item }) => (
{item.name}
);
return (
item.id}
renderItem={renderItem}
ListEmptyComponent={
No results found
}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
ItemSeparatorComponent={() => }
/>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
},
input: {
borderWidth: 1,
borderColor: "#ccc",
borderRadius: 8,
padding: 12,
marginBottom: 16,
},
itemContainer: {
padding: 16,
backgroundColor: "#fff",
},
itemText: {
fontSize: 16,
},
separator: {
height: 1,
backgroundColor: "#eee",
},
emptyText: {
textAlign: "center",
color: "#666",
marginTop: 20,
fontSize: 16,
},
});
export default SearchableList;
Question 6
Create a LoginForm
component with TextInput
fields for email and password. Implement basic validation: the email must include “@” and the password must be at least 6 characters long.
import React from 'react';
import { View, TextInput, Button } from 'react-native';
// Implement LoginForm component here
Answer:
import React, { useState } from 'react';
import { View, TextInput, Button, Alert, Text, StyleSheet } from 'react-native';
const LoginForm = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [emailError, setEmailError] = useState(false);
const [passwordError, setPasswordError] = useState(false);
const validateForm = () => {
let isValid = true;
const emailValid = email.includes('@') && email.trim().length > 0;
setEmailError(!emailValid);
const passwordValid = password.trim().length >= 6;
setPasswordError(!passwordValid);
if (emailValid && passwordValid) {
Alert.alert('Success', 'Login successful!');
} else {
isValid = false;
}
return isValid;
};
return (
<View style={styles.container}>
<TextInput
placeholder="Email"
value={email}
onChangeText={setEmail}
autoCapitalize="none"
keyboardType="email-address"
style={[styles.input, emailError && styles.errorBorder]}
placeholderTextColor="#999"
/>
{emailError && (
<Text style={styles.errorText}>Please enter a valid email address</Text>
)}
<TextInput
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
style={[styles.input, passwordError && styles.errorBorder]}
placeholderTextColor="#999"
/>
{passwordError && (
<Text style={styles.errorText}>Password must be at least 6 characters</Text>
)}
<Button
title="Login"
onPress={validateForm}
color="#007AFF"
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
padding: 20,
backgroundColor: '#fff',
},
input: {
height: 50,
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 8,
paddingHorizontal: 15,
marginBottom: 10,
fontSize: 16,
},
errorBorder: {
borderColor: 'red',
},
errorText: {
color: 'red',
marginBottom: 10,
fontSize: 14,
},
});
export default LoginForm;
Question 7
Design a custom MyButton
component that accepts title
and onPress
props and styles the button with a blue background and white text.
import React from 'react';
import { TouchableOpacity, Text } from 'react-native';
// Implement MyButton component here
Answer:
import React from 'react';
import { TouchableOpacity, Text, StyleSheet } from 'react-native';
const MyButton = ({ title, onPress }) => (
{title}
);
const styles = StyleSheet.create({
button: { backgroundColor: 'blue', padding: 10, borderRadius: 5 },
text: { color: 'white', textAlign: 'center' },
});
export default MyButton;
Question 8
Complete the Stopwatch
component that starts counting seconds when the “Start” button is pressed and stops when the “Stop” button is pressed. Include a “Reset” button to reset the time.
import React from 'react';
import { View, Text, Button } from 'react-native';
// Implement Stopwatch component here
Answer:
import React, { useState, useRef, useEffect } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
const Stopwatch = () => {
const [seconds, setSeconds] = useState(0);
const intervalRef = useRef(null);
const startTimeRef = useRef(0);
useEffect(() => {
return () => stop();
}, []);
const formatTime = (totalSeconds) => {
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
};
const start = () => {
if (!intervalRef.current) {
startTimeRef.current = Date.now() - seconds * 1000;
intervalRef.current = setInterval(() => {
const elapsed = Math.floor((Date.now() - startTimeRef.current) / 1000);
setSeconds(elapsed);
}, 1000);
}
};
const stop = () => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
};
const reset = () => {
stop();
setSeconds(0);
};
return (
<View style={styles.container}>
<Text style={styles.timeText}>{formatTime(seconds)}</Text>
<View style={styles.buttonContainer}>
<Button
title="Start"
onPress={start}
disabled={!!intervalRef.current}
color="#4CAF50"
/>
<Button
title="Stop"
onPress={stop}
disabled={!intervalRef.current}
color="#F44336"
/>
<Button
title="Reset"
onPress={reset}
color="#2196F3"
/>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
timeText: {
fontSize: 48,
fontWeight: 'bold',
marginBottom: 20,
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
width: '80%',
gap: 10,
}
});
export default Stopwatch;
Question 9
Complete the PersistentCounter
component so that it saves the count value using
AsyncStorage
and restores it when the app is reopened.
import React from 'react';
import { View, Text, Button } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
// Implement PersistentCounter component here
Answer:
import React, { useState, useEffect } from 'react';
import { View, Text, Button, StyleSheet, ActivityIndicator } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
const PersistentCounter = () => {
const [count, setCount] = useState(0);
const [loading, setLoading] = useState(true);
// Load saved count on component mount
useEffect(() => {
const loadCount = async () => {
try {
const storedCount = await AsyncStorage.getItem('count');
if (storedCount !== null) {
setCount(Number(storedCount));
}
} catch (error) {
console.error('Error loading count:', error);
} finally {
setLoading(false);
}
};
loadCount();
}, []);
// Save count whenever it changes
useEffect(() => {
const saveCount = async () => {
try {
await AsyncStorage.setItem('count', count.toString());
} catch (error) {
console.error('Error saving count:', error);
}
};
if (!loading) {
saveCount();
}
}, [count, loading]);
const increment = () => setCount(prev => prev + 1);
const decrement = () => setCount(prev => Math.max(0, prev - 1));
const reset = () => setCount(0);
if (loading) {
return (
<View style={styles.container}>
<ActivityIndicator size="large" />
</View>
);
}
return (
<View style={styles.container}>
<Text style={styles.countText}>Count: {count}</Text>
<View style={styles.buttonContainer}>
<Button title="Decrement" onPress={decrement} disabled={count === 0} />
<Button title="Increment" onPress={increment} />
</View>
<Button
title="Reset"
onPress={reset}
color="#FF0000"
disabled={count === 0}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
countText: {
fontSize: 32,
fontWeight
Question 10
Given a ProductList
component, implement it to display a list of products with their names and prices using a FlatList
.
import React from 'react';
import { View, FlatList, Text } from 'react-native';
const products = [
{ id: '1', name: 'Laptop', price: 999 },
{ id: '2', name: 'Smartphone', price: 499 },
// More products...
];
// Implement ProductList component here
Answer:
import React from 'react';
import { View, FlatList, Text } from 'react-native';
const products = [
{ id: '1', name: 'Laptop', price: 999 },
{ id: '2', name: 'Smartphone', price: 499 },
{ id: '3', name: 'Headphones', price: 199 },
];
const ProductList = () => {
return (
item.id}
renderItem={({ item }) => (
{item.name} - ${item.price}
)}
/>
);
};
export default ProductList;
Question 11
Create a ThemeSwitcher
component that toggles between light and dark themes using the useContext
hook.
import React from 'react';
import { View, Button } from 'react-native';
// Implement ThemeContext and ThemeSwitcher component here
Answer:
import React, { useState, createContext, useContext } from 'react';
import { View, Button, Text, StyleSheet } from 'react-native';
const ThemeContext = createContext();
const ThemeProvider = ({ children }) => {
const [isDark, setIsDark] = useState(false);
const toggleTheme = () => setIsDark((prev) => !prev);
return (
<ThemeContext.Provider value={{ isDark, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
const ThemeSwitcher = () => {
const { isDark, toggleTheme } = useContext(ThemeContext);
const themeStyles = isDark ? styles.dark : styles.light;
return (
<View style={[styles.container, themeStyles]}>
<Text style={styles.text}>Current Theme: {isDark ? 'Dark' : 'Light'}</Text>
<Button title="Toggle Theme" onPress={toggleTheme} />
</View>
);
};
const styles = StyleSheet.create({
container: { padding: 20, alignItems: 'center' },
text: { marginBottom: 10 },
light: { backgroundColor: '#fff' },
dark: { backgroundColor: '#333' },
});
export default function App() {
return (
<ThemeProvider>
<ThemeSwitcher />
</ThemeProvider>
);
}
Question 12
Implement a ProgressBar
component that visually represents a progress value between 0 and 100%.
import React from 'react';
import { View } from 'react-native';
// Implement ProgressBar component here
Answer:
import React from 'react';
import { View, StyleSheet } from 'react-native';
const ProgressBar = ({ progress }) => {
return (
);
};
const styles = StyleSheet.create({
container: {
height: 20,
backgroundColor: '#e0e0de',
borderRadius: 10,
overflow: 'hidden',
},
filler: {
height: '100%',
backgroundColor: '#3b5998',
},
});
export default ProgressBar;
Question 13
Write a component ImageCarousel
that displays images in a scrollable horizontal view.
import React from 'react';
import { View } from 'react-native';
// Implement ImageCarousel component here
Answer:
import React from 'react';
import { View, ScrollView, Image, StyleSheet } from 'react-native';
const images = [
{ uri: 'https://via.placeholder.com/150/0000FF/808080' },
{ uri: 'https://via.placeholder.com/150/FF0000/FFFFFF' },
{ uri: 'https://via.placeholder.com/150/FFFF00/000000' },
];
const ImageCarousel = () => {
return (
{images.map((img, index) => (
))}
);
};
const styles = StyleSheet.create({
container: { flexDirection: 'row' },
image: { width: 300, height: 200, marginRight: 10 },
});
export default ImageCarousel;
Question 14
Create a component that uses Modal
to display a pop-up when a button is pressed.
import React from 'react';
import { View, Button } from 'react-native';
// Implement ModalComponent here
Answer:
import React, { useState } from 'react';
import { View, Button, Modal, Text, StyleSheet } from 'react-native';
const ModalComponent = () => {
const [modalVisible, setModalVisible] = useState(false);
return (
<View style={styles.container}>
<Button title="Show Modal" onPress={() => setModalVisible(true)} />
<Modal transparent visible={modalVisible} animationType="slide">
<View style={styles.modalContainer}>
<View style={styles.modalContent}>
<Text>Hello, I am a modal!</Text>
<Button title="Hide Modal" onPress={() => setModalVisible(false)} />
</View>
</View>
</Modal>
</View>
);
};
const styles = StyleSheet.create({
container: { marginTop: 50 },
modalContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
modalContent: { backgroundColor: 'white', padding: 20, borderRadius: 10 },
});
export default ModalComponent;
Question 15
Implement an AnimatedBox
component that changes its opacity from 0 to 1 over 5 seconds when it mounts.
import React from 'react';
import { View } from 'react-native';
// Implement AnimatedBox component here
Answer:
import React, { useEffect, useRef } from 'react';
import { View, Animated, StyleSheet } from 'react-native';
const AnimatedBox = () => {
const fadeAnim = useRef(new Animated.Value(0)).current;
useEffect(() => {
Animated.timing(fadeAnim, { toValue: 1, duration: 5000, useNativeDriver: true }).start();
}, [fadeAnim]);
return ;
};
const styles = StyleSheet.create({
box: { width: 100, height: 100, backgroundColor: 'blue' },
});
export default AnimatedBox;
Question 16
Create a NetworkStatus
component that displays whether the device is online or offline using the NetInfo
API.
import React from 'react';
import { View, Text } from 'react-native';
// Implement NetworkStatus component here
Answer:
import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import NetInfo from '@react-native-community/netinfo';
const NetworkStatus = () => {
const [isConnected, setIsConnected] = useState(null);
useEffect(() => {
const unsubscribe = NetInfo.addEventListener(state => {
setIsConnected(state.isConnected);
});
// Check initial network state
NetInfo.fetch().then(state => {
setIsConnected(state.isConnected);
});
return () => unsubscribe();
}, []);
return (
{isConnected === null
? 'Checking network...'
: `You are ${isConnected ? 'Online' : 'Offline'}`
}
);
};
const styles = StyleSheet.create({
container: {
padding: 10,
},
text: {
fontSize: 16,
textAlign: 'center',
},
});
export default NetworkStatus;
Question 17
Implement a PullToRefresh
component that reloads data when the user pulls down on a ScrollView
.
import React from 'react';
import { ScrollView } from 'react-native';
// Implement PullToRefresh component here
Answer:
import React, { useState } from 'react';
import { ScrollView, RefreshControl, Text, StyleSheet } from 'react-native';
const PullToRefresh = () => {
const [refreshing, setRefreshing] = useState(false);
const [items, setItems] = useState(['Item 1', 'Item 2']);
const onRefresh = () => {
setRefreshing(true);
setTimeout(() => {
setItems(prev => [...prev, `Item ${prev.length + 1}`]);
setRefreshing(false);
}, 2000);
};
return (
}
>
{items.map((item, index) => (
{item}
))}
);
};
const styles = StyleSheet.create({
container: {
flexGrow: 1,
padding: 16
},
item: {
fontSize: 18,
padding: 12,
borderBottomWidth: 1,
borderBottomColor: '#eee'
}
});
export default PullToRefresh;
Question 18
Create a WebViewComponent
that loads a specified URL within the app.
import React from 'react';
import { View } from 'react-native';
// Implement WebViewComponent here
Answer:
import React from 'react';
import { View } from 'react-native';
import { WebView } from 'react-native-webview';
const WebViewComponent = () => {
return ;
};
export default WebViewComponent;
Question 19
Implement a QRCodeScanner
component that uses the device camera to scan QR codes.
import React from 'react';
import { View } from 'react-native';
// Implement QRCodeScanner component here
Answer:
import React from 'react';
import { Alert } from 'react-native';
import QRCodeScanner from 'react-native-qrcode-scanner';
const QRCodeScannerComponent = () => {
const onSuccess = (e) => {
Alert.alert('QR Code Scanned', e.data);
};
return ;
};
export default QRCodeScannerComponent;
Question 20
Create a ClipboardExample
component that copies text to the clipboard when a button is pressed.
import React from 'react';
import { View } from 'react-native';
// Implement ClipboardExample component here
Answer:
import React from 'react';
import { Button, Alert } from 'react-native';
import Clipboard from '@react-native-clipboard/clipboard';
const ClipboardExample = () => {
const copyToClipboard = () => {
Clipboard.setString('Sample text');
Alert.alert('Copied to Clipboard');
};
return <Button title="Copy Text" onPress={copyToClipboard} />;
};
export default ClipboardExample;
React Native Developer hiring resources
Our clients
Popular React Native Development questions
Is Node.js or React Native better?
Node.js is a Back-end runtime environment for executing JavaScript code server-side, while React Native is a Front-end framework for building mobile applications. They serve different purposes and are often used together in Full-stack development.
What is React Native mainly used for?
React Native is mainly used for developing mobile applications that work on both iOS and Android platforms. It allows developers to build cross-platform apps using a single codebase, enabling faster development and a consistent user experience across different devices.
What programming language does React Native use?
React Native primarily uses JavaScript as its programming language. It also allows developers to write some parts of the app in native languages like Java, Objective-C, or Swift for platform-specific functionality. Additionally, React Native uses JSX, a syntax extension for JavaScript that allows writing UI components in a syntax similar to HTML.
Can you build a website with React Native?
You cannot build a website with React Native. React Native is designed for building mobile applications, not websites. For websites, you would use React.
Is React Native the same as React?
React Native is not the same as React. React is a JavaScript library used for building user interfaces for web applications, while React Native is a framework that allows you to build native mobile apps using React.
Interview Questions by role
Interview Questions by skill
Interview Questions
Interview Questions
Interview Questions
Interview Questions
Interview Questions
Interview Questions
Interview Questions
Interview Questions
Interview Questions
Interview Questions
Interview Questions
Interview Questions
Interview Questions
Interview Questions
Interview Questions
Interview Questions
Interview Questions