Intermediate React Native Interview Questions and Answers
25. How to upgrade react-native to the latest version on your system?
We can directly install the newer version by specifying the version number as shown before in this article. Or else we can run the following commands.
react-native upgrade
react-native init
26. How can we use firebase in react-native?
We can use firebase in react native by following the given steps
- Create a project in firebase.
- Install the firebase tools using npm - npm install -g firebase-tools
- Take the credentials from project settings in firebase.
- Add them to the environment file.
27. How to import components in react-native?
We can import components in react by using the import statement and path of the component, as shown below.
Import { bodyComponent } from “./src/app/body/body.component”;
28. What is the Virtual DOM in React Native?
The Virtual DOM is an in-memory representation of the real DOM elements. When the state or props of a component change, React Native updates the Virtual DOM first and calculates the minimal changes required to apply to the real DOM, enhancing performance and efficiency.
29. How does React Native bridge work?
The React Native bridge is a core part of the framework that enables communication between the JavaScript thread and the native thread. It allows JavaScript code to invoke native modules and components, and vice versa. The bridge serializes data between the two realms, ensuring that React components can interact with native platform APIs and UI elements.
30. How do you optimize the performance of a React Native application?
To optimize performance in React Native:
- Use FlatList or SectionList for rendering large datasets.
- Avoid unnecessary re-renders using React.memo() and PureComponent.
- Minimize the use of anonymous functions in the render() method.
- Use lazy loading and code splitting for components.
31. What is the difference between React Native and React?
React Native is a framework for building mobile applications using React and JavaScript. It allows you to create native mobile apps for iOS and Android platforms. React, on the other hand, is a JavaScript library for building user interfaces, primarily for web applications. While both use React's component-based architecture, React Native provides additional tools and APIs specific to mobile development.
32. What are some common ways to manage state in React Native?
State management can be handled using:
- React’s built-in useState() and useReducer().
- Third-party libraries like Redux, MobX, or Zustand.
- Context API for global state management.
33. What are the main components of React Native architecture?
The main components of React Native architecture include:
- JavaScript Core: Runs the JavaScript code
- Bridge: Facilitates communication between JavaScript and native code
- Native Modules: Platform-specific APIs and functionalities
- Renderers: Handle rendering of components on different platforms
- Shadow Tree: Manages layout calculations
34. Explain the difference between a controlled and an uncontrolled component.
A controlled component is one where the form data is handled by the component's state, while an uncontrolled component uses a ref to access form values directly from the DOM.
35. How do you implement gestures in React Native?
Gestures in React Native can be implemented using:
- React Native's built-in PanResponder for basic gestures.
- Libraries like react-native-gesture-handler for more advanced gesture handling.
36. What is the purpose of the Metro bundler in React Native?
Metro is the JavaScript bundler used by React Native. Its main purposes are:
- Transforming and bundling JavaScript code
- Providing a development server for hot reloading
- Handling asset management (images, fonts, etc.)
- Generating source maps for debugging
- Supporting different bundle formats for various platforms
37. How do you handle deep linking in React Native?
Deep linking allows the app to open specific screens from a URL. In React Native, you can handle deep linking using:
- React Navigation’s deep linking configuration.
- Linking API for URL event handling.
38. What are the differences between ScrollView and FlatList?
- ScrollView renders all its child components at once, while FlatList renders items lazily.
- ScrollView is better for a small number of items, while FlatList is optimized for long lists.
- FlatList provides built-in performance optimizations like windowing and item recycling.
- ScrollView can scroll both vertically and horizontally, while FlatList is primarily designed for vertical lists (though horizontal scrolling is possible).
39. How do you persist data in a React Native application?
Data persistence can be handled using:
- AsyncStorage for local storage.
- SecureStore for secure data storage.
- Third-party libraries like react-native-mmkv or realm for larger datasets.
40. How do you handle platform-specific code in React Native?
Platform-specific code can be handled in several ways:
- Using the Platform module to check the current platform
- Using platform-specific file extensions (e.g., Component.ios.js and Component.android.js)
- Using the Platform.select method to return platform-specific values
- Creating platform-specific components or modules and importing them conditionally
41. What is the difference between React Native CLI and Expo?
React Native CLI provides full control over the native code, allowing customization but requiring more setup. Expo abstracts much of the complexity, offering an easier setup at the cost of limited native module access.
42. What are Animated and LayoutAnimation in React Native?
Animated is a library in React Native for creating fluid, powerful, and flexible animations. It provides fine-grained control over animations and supports interpolations, parallel animations, and native driver for better performance.
LayoutAnimation is a way to animate layout changes globally for the entire component hierarchy. It's simpler to use than Animated but less flexible. It's particularly useful for animating the addition or removal of components.
43. How do you debug a React Native app?
React Native apps can be debugged using:
- React Native Debugger.
- Chrome Developer Tools with Remote Debugging.
- Flipper (for advanced debugging and inspection).
44. How do you implement dark mode in a React Native app?
To implement dark mode in a React Native app:
- Create separate style objects for light and dark themes
- Use the Appearance API to detect the user's preferred color scheme
- Create a context to manage and provide the current theme
- Use the useColorScheme hook to react to system theme changes
- Apply theme-specific styles to components based on the current theme
45. What is the difference between useEffect() and useLayoutEffect()?
useEffect() runs asynchronously after a render, while useLayoutEffect() runs synchronously after the DOM updates but before the browser paints. useLayoutEffect() is typically used for layout calculations.
46. What is the purpose of babel.config.js in a React Native project?
The babel.config.js file in a React Native project configures Babel, the JavaScript compiler. It specifies how to transform your JavaScript code, including:
- Setting the appropriate presets for React Native
- Configuring plugins for additional language features or optimizations
- Defining environment-specific transformations
- Setting up module resolver aliases
47. What are the lifecycle methods of React components in React Native?
Class components have lifecycle methods like componentDidMount(), componentDidUpdate(), and componentWillUnmount(). In functional components, these methods are replaced by the useEffect() Hook.
48. What are the key differences between useState and useReducer hooks?
- useState is simpler and suitable for managing independent pieces of state
- useReducer is better for complex state logic, especially when state transitions depend on previous state
- useReducer allows for centralized state update logic
- useState updates state directly, while useReducer dispatches actions to update state
- useReducer can be more performant for components with many state updates
49. What is the purpose of StyleSheet.create() in React Native?
StyleSheet.create() is used to create optimized, immutable style objects, improving performance by reducing re-render costs during style changes.
50. What is the purpose of the metro.config.js file?
The metro.config.js file is used to configure the Metro bundler in a React Native project. It allows you to:
- Customize the bundling process
- Define asset handling rules
- Configure source map generation
- Set up module resolution aliases
- Modify transformation rules for different file types
- Configure caching behavior
Advanced React Native Interview Questions and Answers
51. How do you make network requests in React Native?
Network requests can be made using:
- The built-in fetch() API.
- Axios, a popular third-party library for handling HTTP requests.
52. How do you handle offline capabilities in a React Native app?
Offline capabilities in a React Native app can be implemented by:
- Using libraries like Redux Offline or React Query for offline data management
- Implementing local storage solutions like AsyncStorage or Realm
- Utilizing service workers for caching assets and API responses
- Implementing sync mechanisms to reconcile local and server data when online
- Using NetInfo to detect and react to network status changes
- Implementing offline-first architecture and optimistic UI updates
53. How do you handle animations in React Native?
Animations can be handled using:
- The Animated API for basic animations.
- Libraries like react-native-reanimated for more complex animations.
54. What are the best practices for handling forms in React Native?
Best practices for handling forms in React Native include:
- Using libraries like Formik or React Hook Form for form management
- Implementing proper validation using libraries like Yup or custom validation logic
- Using controlled components for form inputs
- Implementing proper keyboard handling and focus management
- Using appropriate input types and keyboard configurations
- Providing clear error messages and visual feedback
55. How do you test React Native components?
Testing React Native components can be done using:
- Jest for unit and snapshot testing.
- React Native Testing Library for more robust testing of components and user interactions.
- Detox or Appium for end-to-end testing.
56. How do you handle app versioning and updates in React Native?
App versioning and updates in React Native can be managed by:
- Using semantic versioning for your app
- Implementing over-the-air (OTA) updates using services like CodePush or Expo Updates
- Configuring proper version codes and build numbers in android/app/build.gradle and ios/YourApp.xcodeproj
- Implementing version checks and forced updates when necessary
- Using tools like Fastlane for automating the release process
- Implementing proper changelog management
57. What is the role of KeyExtractor in FlatList?
KeyExtractor is a prop in FlatList that provides a unique key for each list item, helping React identify which items need re-rendering and improving list performance.
58. What is the purpose of the Hermes engine in React Native?
Hermes is a JavaScript engine optimized for React Native. Its purposes include:
- Improving app start-up time
- Reducing memory usage
- Decreasing app size
- Improving overall app performance
- Providing better support for synchronous initialization
59. How do you handle errors in React Native?
Error handling in React Native can be done using:
- try-catch blocks for synchronous code.
- Promises and .catch() for asynchronous code.
- Error boundaries for handling UI-related errors.
60. What are the key considerations when designing a React Native app for multiple screen sizes?
When designing for multiple screen sizes:
- Use responsive design principles and flexbox layouts
- Implement adaptive layouts using Dimensions API or libraries like react-native-responsive-screen
- Use density-independent pixels (dp) for consistent sizing across devices
- Create separate layouts for tablets or implement responsive components
- Use the SafeAreaView component to handle notches and rounded corners
- Test on various device sizes and orientations
61. How do you use TypeScript with React Native?
TypeScript can be used by installing TypeScript and configuring the tsconfig.json file. You can then use .tsx files and take advantage of TypeScript’s type checking and IntelliSense.
62. What are the main differences between class components and functional components in React Native?
Main differences include:
- Syntax: Class components use ES6 classes, while functional components are JavaScript functions
- State management: Class components use this.state, while functional components use hooks like useState
- Lifecycle methods: Class components have lifecycle methods, while functional components use the useEffect hook
- Performance: Functional components can be more performant due to optimizations like avoiding bind in renders
- Code reusability: Functional components make it easier to reuse stateless logic through custom hooks
63. What are higher-order components (HOC) in React Native?
A higher-order component (HOC) is a function that takes a component as an argument and returns a new component. It is used to share logic between components without repeating code.
64. How do you handle authentication in a React Native app?
Authentication in a React Native app can be handled by:
- Implementing JWT (JSON Web Token) based authentication
- Using OAuth 2.0 for third-party authentication providers
- Storing authentication tokens securely using Keychain for iOS and EncryptedSharedPreferences for Android
- Implementing proper token refresh mechanisms
- Using libraries like react-native-auth0 or expo-auth-session for simplified auth flows
- Implementing biometric authentication using react-native-touch-id or react-native-fingerprint-scanner
65. How do you handle push notifications in React Native?
Push notifications can be handled using:
- Firebase Cloud Messaging (FCM) along with react-native-firebase.
- Local notifications using the react-native-push-notification library.
66. How do you optimize image loading and caching in React Native?
To optimize image loading and caching:
- Use libraries like react-native-fast-image for better performance and caching
- Implement lazy loading for images, especially in lists
- Use appropriate image formats and compress images when possible
- Implement placeholder images or skeleton screens while loading
- Use the resizeMode prop to control how images are scaled
- Implement proper error handling for failed image loads
- Consider using a content delivery network (CDN) for faster image delivery
67. What is the difference between useRef() and createRef() in React Native?
useRef() is used in functional components to persist a value across renders without causing re-renders. createRef() is used in class components to create a reference to a DOM element or React component.
68. How do you handle internationalization (i18n) in React Native?
Internationalization in React Native can be implemented by:
- Using libraries like react-native-localize or i18next
- Storing translations in JSON files or a CMS
- Implementing a language switcher in the app settings
- Using the Intl API for number and date formatting
- Considering right-to-left (RTL) layout support for certain languages
- Implementing pluralization and context-aware translations
69. How do you handle app crashes in production for React Native apps?
App crashes can be handled using crash reporting tools like:
- Firebase Crashlytics.
- Sentry. These tools capture crash reports and provide insights to resolve production issues.
70. How does React Native handle concurrent rendering?
React Native's approach to concurrent rendering differs from React on the web due to the constraints of mobile platforms:
- Single-Threaded Execution: JavaScript runs on a single thread in React Native, limiting true concurrency.
- Native UI Thread: UI updates must happen on the main native thread.
- Bridge Communication: The asynchronous nature of the bridge affects how updates are processed.
React Native uses a batching mechanism to group updates and minimize bridge communication. The new architecture (Fabric) aims to improve this by allowing more synchronous operations.
71. How do you optimize memory usage in React Native apps?
Memory optimization can be achieved by:
- Avoiding large, unused objects in memory.
- Using lazy loading for large components.
- Implementing image caching with libraries like react-native-fast-image.
- Optimizing list rendering with FlatList and VirtualizedList.
72. How would you implement a custom renderer for React Native?
Implementing a custom renderer for React Native involves several complex steps:
-
Create a Custom Host Config:
- Implement methods like createInstance, appendChild, removeChild, etc.
- Define how elements are created, updated, and managed.
-
Implement Reconciliation:
- Create a custom reconciler using react-reconciler package.
- Define how updates are processed and applied to your custom elements.
-
Create a Root Container:
- Implement a root container that serves as the entry point for your renderer.
-
Bridge Native and JavaScript:
- Implement a communication layer between your custom native elements and React.
-
Handle Layout and Styling:
- Implement a system to manage layout and apply styles to your custom elements.
-
Implement Event Handling:
- Create a system to propagate native events to React components.
-
Optimize Performance:
- Implement batching and other optimizations to ensure efficient updates.
73. What is Fabric in React Native?
Fabric is a new rendering system in React Native that improves performance by introducing a synchronous bridge between JavaScript and native code. It enables faster UI updates and smoother animations.
74. Describe the process of implementing a custom gesture handler in React Native.
Implementing a custom gesture handler involves several steps:
1. Create a new native component (iOS and Android) that extends RCTViewManager:iOS:
@objc(RCTCustomGestureHandler)
class CustomGestureHandler: RCTViewManager {
override func view() -> UIView! {
return CustomGestureView()
}
}
Android:
public class CustomGestureHandler extends ViewGroupManager<CustomGestureView> {
@Override
public String getName() {
return "CustomGestureHandler";
}
@Override
protected CustomGestureView createViewInstance(ThemedReactContext reactContext) {
return new CustomGestureView(reactContext);
}
}
2. Implement the custom view with gesture recognition: iOS:
class CustomGestureView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
let gesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
self.addGestureRecognizer(gesture)
}
@objc func handlePan(_ gesture: UIPanGestureRecognizer) {
// Handle the gesture
}
}
Android:
public class CustomGestureView extends ViewGroup {
private GestureDetectorCompat gestureDetector;
public CustomGestureView(Context context) {
super(context);
gestureDetector = new GestureDetectorCompat(context, new GestureListener());
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event) || super.onTouchEvent(event);
}
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
// Implement gesture methods
}
}
3. Expose properties and events to JavaScript:
import { requireNativeComponent, ViewPropTypes } from 'react-native';
import PropTypes from 'prop-types';
const CustomGestureHandler = requireNativeComponent('CustomGestureHandler', {
propTypes: {
...ViewPropTypes,
onGestureEvent: PropTypes.func,
},
});
export default CustomGestureHandler;
4. Use the custom gesture handler in your React Native component:
import React from 'react';
import CustomGestureHandler from './CustomGestureHandler';
const MyComponent = () => {
const handleGesture = (event) => {
// Handle the gesture event
};
return (
<CustomGestureHandler onGestureEvent={handleGesture}>
{/* Child components */}
</CustomGestureHandler>
);
};
75. How do you handle large datasets efficiently in React Native?
Handling large datasets efficiently can be done using:
- FlatList or SectionList for lazy loading and rendering.
- Pagination techniques to load data incrementally.
- Memoizing list items using React.memo() or PureComponent.
76. How does React Native handle threading?
React Native's threading model is designed to maintain a responsive UI while executing JavaScript code:
-
Main Thread (Native UI Thread):
- Handles UI rendering and updates
- Manages touch events and native animations
-
JavaScript Thread:
- Runs the JavaScript bundle
- Executes React reconciliation and app logic
-
Shadow Thread (in new architecture):
- Performs layout calculations
- Prepares updates for the main thread
-
Background Threads:
- Handle various tasks like image processing, network requests, etc.
77. How does the Reconciler in React Native work?
The Reconciler is the part of React that compares the Virtual DOM with the real DOM. When a change occurs, the Reconciler finds the minimal set of changes to apply, making updates efficient and minimizing performance overhead.
78. Explain the concept of "Fast Refresh" in React Native.
Fast Refresh is a React Native feature that provides near-instant feedback for changes in your React components. Key aspects:
- Component-Level Updates: Preserves component state for the changed component and its parents.
- Resilient to Errors: Recovers gracefully from syntax or runtime errors.
- Hooks Support: Fully supports functional components and hooks.
- Global State Preservation: Maintains global state across refreshes.
79. What are Turbo Modules in React Native?
Turbo Modules is a new architecture introduced in React Native to improve module loading. It enables lazy loading of native modules, which speeds up app startup time and reduces memory usage.
80. What are the differences between fast refresh and hot reloading?
There are several differences between fast refresh and hot reloading:
- Consistency: Fast Refresh is more consistent and reliable in applying updates.
- Error Handling: Fast refresh provides better error recovery and reporting.
- Hooks Support: Hot Reloading had issues with hooks, which Fast Refresh resolves.
- Performance: Fast refresh is faster and more efficient.
- Implementation: Fast Refresh is built into React core, while Hot Reloading is a separate system.
81. How do you reduce the app bundle size in React Native?
Reducing bundle size can be done by:
- Using Proguard (for Android) and Bitcode (for iOS) to remove unused code.
- Enabling Hermes, which is an optimized JavaScript engine.
- Using code-splitting and tree-shaking to remove dead code.
82. Explain the concept of "Codegen" in the new React Native architecture.
Codegen is a tool that:
- Generates type-safe native code from JavaScript specifications
- Improves communication between JS and native code
- Reduces runtime overhead
- Enables static analysis and better tooling
- Is part of the Turbo Modules and Fabric systems
83. What are the common issues with React Native navigation and how do you solve them?
Common issues include:
- Stack overflow errors in nested navigators: Solved by using proper nesting and screens definitions.
- Gesture conflicts: Resolved by using react-native-gesture-handler and customizing gesture priorities.
- Performance issues: Solved by lazy loading screens and optimizing the navigation stack.
84. How do you handle concurrency in React Native?
Concurrency in React Native can be handled using:
- JavaScript’s Promise and async-await for asynchronous operations.
- Multithreading via react-native-threads for CPU-intensive tasks.
- Background services for offloading tasks, using libraries like react-native-background-task.
85. How would you implement a custom video player in React Native?
- Use react-native-video as a base
- Create a wrapper component for custom controls
- Implement play/pause, seek, and volume controls
- Add full-screen toggle functionality
- Handle orientation changes
- Implement buffering indicator
- Add support for different video formats
- Optimize for performance and battery usage
86. What is Proguard, and how do you configure it in React Native?
Proguard is a tool used in Android to shrink, optimize, and obfuscate the code, reducing app size. In React Native, Proguard can be enabled by adding the following to android/app/build.gradle:
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
87. Explain the concept of "Flipper" and its role in React Native development.
Flipper is a debugging platform that:
- Provides a desktop interface for mobile app debugging
- Offers plugins for network inspection, crash reporting, etc.
- Allows real-time manipulation of app state
- Supports custom plugins for specific debugging needs
- Integrates with React Native development workflow
88. What is a forward ref in React Native?
A forward ref is a technique that allows a parent component to pass a ref to its child component. It is used when you need access to a child component’s instance, typically for managing focus, animations, or integrating with native components.
89. Describe the process of implementing a custom drawing/signature pad in React Native.
- Create a native module for drawing functionality
- Implement touch handling in native code
- Use PanResponder in React Native for gesture recognition
- Render drawing on a Canvas component
- Implement stroke smoothing algorithm
- Add options for stroke color and width
- Provide methods to clear and save drawings
90. What is the difference between synchronous and asynchronous bridges in React Native?
Synchronous bridges allow JavaScript to communicate with native code in real-time, while asynchronous bridges queue and batch communication. Asynchronous bridges are less prone to blocking UI threads and are more performance-efficient.
React Native Interview MCQs
1. Which of the following is true about React Native?
a) It is used for web development.
b) It uses native components for building mobile apps.
c) It is purely a JavaScript library for backend development.
d) It is a database management system.
Answer: b) It uses native components for building mobile apps.
2. Which of the following command is used to create a new React Native project?
a) react-native start
b) react-native init
c) react-native new
d) react-native create
Answer: b) react-native init
3. How can you optimize images in a React Native application?
a) By reducing their pixel density.
b) By converting them to vector format.
c) By using Image.getSize() and caching libraries like react-native-fast-image.
d) By removing require() function from image imports.
Answer: c) By using Image.getSize() and caching libraries like react-native-fast-image.
4. Which method is used to fetch data in React Native applications?
a) getData()
b) fetch()
c) retrieve()
d) obtain()
Answer: b) fetch()
5. What is the default thread used by React Native for JavaScript execution?
a) UI Thread
b) Main Thread
c) Native Thread
d) JS Thread
Answer: d) JS Thread
6. How does React Native achieve platform-specific code?
a) By using Platform.select()
b) By using Platform.os()
c) By using OSSpecific()
d) By using NativeCode()
Answer: a) By using Platform.select()
7. Which library is commonly used for navigation in React Native applications?
a) react-router
b) react-native-navigation
c) react-navigation
d) react-location
Answer: c) react-navigation
8. What is the purpose of useEffect() in React Native?
a) To handle animations
b) To handle side effects in functional components
c) To manage state
d) To handle component styles
Answer: b) To handle side effects in functional components
9. What is the command to run an iOS React Native application in a simulator?
a) npm run-ios
b) react-native ios
c) react-native run-ios
d) react-native-ios start
Answer: c) react-native run-ios
10. Which JavaScript engine is optimized for React Native?
a) SpiderMonkey
b) V8
c) Chakra
d) Hermes
Answer: d) Hermes
Conclusion
In this article, we have discussed React Native Interview Questions. Preparing for a React Native interview requires a solid understanding of both React fundamentals and mobile development concepts. The discussed questions will help you review essential topics like components, state management, navigation, and platform-specific APIs.
Recommended Readings:
You can also consider our React Js Course to give your career an edge over others.
Happy Coding!