React Native Interview Questions

Unlock the potential of React Native with 'React Native Interview Questions.' This blog is your ultimate resource for preparing for React Native-related interviews, featuring a comprehensive collection of questions and detailed answers. Whether you're a mobile app developer, a front-end engineer, or a React Native enthusiast, our guide covers React Native fundamentals, component-based development, navigation, and best practices. Prepare with confidence and explore the world of cross-platform mobile app development with React Native.

1. What is React Native?

React Native is a framework for building mobile applications using React and JavaScript. It allows developers to use React along with native capabilities to create cross-platform mobile apps.

2. Explain the difference between React and React Native.

React is a JavaScript library for building user interfaces, primarily for web applications. React Native, on the other hand, extends React to enable the development of mobile applications for iOS and Android.

3. Code Snippet: Creating a React Native Component

            
// Sample React Native Component
import React from 'react';
import { View, Text } from 'react-native';

const HelloWorldApp = () => {
  return (
    
      Hello, World!
    
  );
};

export default HelloWorldApp;
            
        

4. What is Flexbox and describe any elaborate on its most used properties?

It is a layout model that allows elements to align and distribute space within a container. With Flexbox when Using flexible widths and heights, all the inside the main container can be aligned to fill a space or distribute space between elements, which makes it a great tool to use for responsive design systems.

Property  Values Description
flexDirection ‘column’,'row' Used to specify if elements will be aligned vertically or horizontally 
justifyContent ‘center’,'flex-start','flex-end','space-around','space-between' Used to determine how should elements be distributed inside the container 
alignItems ‘center’,'flex-start','flex-end','stretched' Used to determine how should elements be distributed inside the container along the secondary axis (opposite of flexDirection)

5. Describe advantages of using React Native?

There are multiple advantage of using React Native like,

6. Are default props available in React Native and if yes for what are they used and how are they used ?

Yes, default props available in React Native as they are for React,  If for an instance we do not pass props value, the component will use the default props value.

import React, {Component} from 'react';

import {View, Text} from 'react-native';class DefaultPropComponent extends Component {   render() {       return (            <View>             <Text>               {this.props.name}             </Text>           </View>       )   }}Demo.defaultProps = {   name: 'BOB'}export default DefaultPropComponent;

7. How is user Input Handled in React Native ?

TextInput is a Core Component that allows the user to enter text. It has an onChangeText prop that takes a function to be called every time the text changes, and an onSubmitEditing prop that takes a function to be called when the text is submitted.

import React, { useState } from 'react';import { Text, TextInput, View } from 'react-native';const PizzaTranslator = () => { const [text, setText] = useState(''); return (   <View style={{padding: 10}}>     <TextInput       style={{height: 40}}       placeholder="Type here to translate!"       onChangeText={text => setText(text)}       defaultValue={text}     />     <Text style={{padding: 10, fontSize: 42}}>       {text.split(' ').map((word) => word && '🍕').join(' ')}     </Text>   </View> );}export default PizzaTranslator;

8. What is State and how is it used in React Native?

It is used to control the components. The variable data can be stored in the state. It is mutable means a state can change the value at any time.

import React, {Component} from 'react';    import { Text, View } from 'react-native';    export default class App extends Component {     state = { myState: 'State of Text Component'              }updateState = () => this.setState({myState: 'The state is updated'})render() {return (<View>    <Text onPress={this.updateState}> {this.state.myState} </Text>    </View> ); } }

Here we create a Text component with state data. The content of the Text component will be updated whenever we click on it. The state is updated by event onPress .

9. Describe Timers in React Native Application ?

Timers are an important and integral part of any application and React Native implements the browser timers.

Timers
 

There may be business requirements to execute a certain piece of code after waiting for some time duration or after a delay setTimeout can be used in such cases, clearTimeout is simply used to clear the timer that is started.

setTimeout(() => {yourFunction();}, 3000);

setInterval is a method that calls a function or runs some code after specific intervals of time, as specified through the second parameter.

setInterval(() => {console.log('Interval triggered');}, 1000);

A function or block of code that is bound to an interval executes until it is stopped. To stop an interval, we can use the clearInterval() method.

Calling the function or execution as soon as possible.

var immediateID = setImmediate(function);// The below code displays the alert dialog immediately.var immediateId = setImmediate(    () => {    alert('Immediate Alert');}

clearImmediate  is used for Canceling the immediate actions that were set by setImmediate().

It is the standard way to perform animations.

Calling a function to update an animation before the next animation frame.

var requestID = requestAnimationFrame(function);// The following code performs the animation.var requestId = requestAnimationFrame(    () => { // animate something})

cancelAnimationFrame is used for Canceling the function that was set by requestAnimationFrame().

10. List down Key Points to integrate React Native in an existing Android mobile application

Primary points to note to integrating React Native components into your Android application are to:

11. How is the entire React Native code processed to show the final output on a mobile screen

12. Name core Components in React Native and the analogy of those components when compared with the web .

The core components used in React Native are <View> , <Text> , <Image> , <ScrollView> , <TextInput>

And analogy when compared Web can be explained by below diagram:

REACT NATIVE UI COMPONENT ANDROID VIEW IOS VIEW WEB ANALOG DESCRIPTION
<View> <ViewGroup> <UIView> A non-scrolling <div> A container that supports layout with flexbox style, some touch handling, and accessibility controls.
<Text> <TextView> <UITextView> <p> Displays, styles, and nests strings of text and even handles touch events.
<Image> <ImageView> <UIImageView> <img> Displays different types of images
<ScrollView> <ScrollView> <UIScrollView> <div> A generic scrolling container that can contain multiple components and views.
<TextInput> <EditText> <UITextField> <input type="text"> Allows the user to enter text

13. What is ListView and describe its use in React Native ?

React Native ListView is a view component that contains the list of items and displays it in a vertically scrollable list.

export default class MyListComponent extends Component {  constructor() {  super();  const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});  this.state = {  dataSource: ds.cloneWithRows(['Android','iOS', 'Java','Php', 'Hadoop', 'Sap', 'Python','Ajax', 'C++']), };}  render() {  return ( <ListView dataSource={this.state.dataSource}  renderRow={  (rowData) =>  <Text style={{fontSize: 30}}>{rowData}</Text>} />  ); }  }

14. How can you write different code for IOS and Android in the same code base ? Is there any module available for this ?

The platform module detects the platform in which the app is running.

import { Platform, Stylesheet } from 'react-native';const styles = Stylesheet.create({height: Platform.OS === 'IOS' ? 200 : 400})

Additionally Platform.select method available that takes an object containing Platform.OS as keys and returns the value for the platform you are currently on.

import { Platform, StyleSheet } from 'react-native';const styles = StyleSheet.create({ container: {flex: 1,   ...Platform.select({     ios: {       backgroundColor: 'red',     },     android: {       backgroundColor: 'green',     },     default: {       // other platforms, web for example       backgroundColor: 'blue',     },    }),},});

15. What are Touchable components in react Native and which one to use when ?

Tapping gestures can be captured by Touchable components and can display feedback when a gesture is recognized.

Depending on what kind of feedback you want to provide we choose Touchable Components.

Generally, we use TouchableHighlight anywhere you would use a button or link on the web. The background of the view will be darkened when the user presses down on the button.

We can use TouchableNativeFeedback on Android to display ink surface reaction ripples that respond to the user's touch.

TouchableOpacity can be used to provide feedback by reducing the opacity of the button, allowing the background to be seen through while the user is pressing down.

If we need to handle a tap gesture but you don't want any feedback to be displayed, use TouchableWithoutFeedback.

import React, { Component } from 'react';import { Platform, StyleSheet, Text, TouchableHighlight, TouchableOpacity, TouchableNativeFeedback, TouchableWithoutFeedback, View } from 'react-native';export default class Touchables extends Component {_onPressButton() {   alert('You tapped the button!')  } _onLongPressButton() {   alert('You long-pressed the button!') }render() {return (<View style={styles.container}><TouchableHighlight onPress={this._onPressButton} underlayColor="white"><View style={styles.button}><Text style={styles.buttonText}>TouchableHighlight</Text></View></TouchableHighlight>);}}

16. Explain FlatList components, what are its key features along with a code sample ?

The FlatList component displays similarly structured data in a scrollable list. It works well for large lists of data where the number of list items might change over time.

Key Feature:

The FlatList shows only those rendered elements which are currently displaying on the screen, not all the elements of the list at once.

import React, { Component } from 'react';  import { AppRegistry, FlatList,     StyleSheet, Text, View,Alert } from 'react-native';  export default class FlatListBasics extends Component {      renderSeparator = () => {         return (             <View                 style={{                     height: 1,                     width: "100%",                     backgroundColor: "#000",                 }}             />         );     };     //handling onPress action     getListViewItem = (item) => {         Alert.alert(item.key);     }      render() {         return (             <View style={styles.container}>                 <FlatList                     data={[                         {key: 'Android'},{key: 'iOS'}, {key: 'Java'},{key: 'Swift'},                         {key: 'Php'},{key: 'Hadoop'},{key: 'Sap'},                     ]}                     renderItem={({item}) =>                         <Text style={styles.item}                               onPress={this.getListViewItem.bind(this, item)}>{item.key}</Text>}                     ItemSeparatorComponent={this.renderSeparator}                 />             </View>         );     }  }  AppRegistry.registerComponent('AwesomeProject', () => FlatListBasics);  

17. How To Use Routing with React Navigation in React Native ?

One of the popular libraries for routing and navigation in a React Native application is React Navigation.

This library helps solve the problem of navigating between multiple screens and sharing data between them.

import * as React from 'react';import { NavigationContainer } from '@react-navigation/native';import { createStackNavigator } from '@react-navigation/stack';const Stack = createStackNavigator();const MyStack = () => { return (   <NavigationContainer>     <Stack.Navigator>       <Stack.Screen         name="Home"         component={HomeScreen}         options={{ title: 'Welcome' }}       />       <Stack.Screen name="Profile" component={ProfileScreen} />     </Stack.Navigator>   </NavigationContainer> );};

18. Explain Async Storage in React Native and also define when to use it and when to not?

DO USE ASYNC STORAGE WHEN.. DON'T USE ASYNC STORAGE FOR..
Persisting non-sensitive data across app runs Token storage
Persisting Redux state Secrets
Persisting GraphQL state  
Storing global app-wide variables  

19. What’s the real cause behind performance issues in React Native ?

The real cause behind React Native performance issues is that each thread (i.e Native and JS thread) is blazingly fast. The performance bottleneck in React Native app occurs when you’re passing the components from one thread to another unnecessarily or more than required. A major thumb rule to avoid any kind of performance-related issue in React Native is to keep the passes over the bridge to a minimum. 

20. List down some of the steps to optimize the application.

21. Describe Memory leak Issue in React Native , how can it be detected and resolved ?

In JavaScript memory is managed automatically by Garbage Collector (GC). In short, Garbage Collector is a background process that periodically traverses the graph of allocated objects and their references. If it happens to encounter a part of the graph that is not being referenced directly or indirectly from root objects (e.g., variables on the stack or a global object like window or navigator) that whole part can be deallocated from the memory.

In React Native world each JS module scope is attached to a root object. Many modules, including React Native core ones, declare variables that are kept in the main scope (e.g., when you define an object outside of a class or function in your JS module). Such variables may retain other objects and hence prevent them from being garbage collected.

Some Causes of Memory Leak:

Detecting memory leaks for IOS:

In Xcode,

Go to XCode → Product → Profile (⌘ + i)

After that shows you all templates choose leaks.

Detecting memory leaks for Android :

Run React Native app normally (react-native run-android)
Run Android Studio

On the menu,
click Tools → Android → Enable ADB Integration
Click Tools → Android → Android Device Monitor
When Android Device Monitor shows up, click Monitor → Preferences

There is also one more way in Android
Perf Monitor (Performance Monitor) is a good choice to use for android leak monitoring.

Import PerfMonitor from 'react-native/Libraries/Performance/RCTRenderingPerf';PerfMonitor.toggle();PerfMonitor.start();setTimeout(() => { PerfMonitor.stop();}, 20000);}, 5000);

22. Is there any out of the box way storing sensitive data in React ? If yes which and if not how can this be achieved ?

React Native does not come bundled with any way of storing sensitive data. However, there are pre-existing solutions for Android and iOS platforms.

iOS - Keychain Services
Keychain Services allows you to securely store small chunks of sensitive info for the user. This is an ideal place to store certificates, tokens, passwords, and any other sensitive information that doesn’t belong in Async Storage.

Android - Secure Shared Preferences#
Shared Preferences is the Android equivalent for a persistent key-value data store. Data in Shared Preferences is not encrypted by default, but Encrypted Shared Preferences wraps the Shared Preferences class for Android, and automatically encrypts keys and values.

Android - Keystore
The Android Keystore system lets you store cryptographic keys in a container to make it more difficult to extract from the device. In order to use iOS Keychain services or Android Secure Shared Preferences, you can either write a bridge yourself or use a library that wraps them for you and provides a unified API at your own risk. Some libraries to consider:

23. Explain setNativeProps. Does it create Performance issues and how is it used ?

It is sometimes necessary to make changes directly to a component without using state/props to trigger a re-render of the entire subtree. When using React in the browser, for example, you sometimes need to directly modify a DOM node, and the same is true for views in mobile apps. setNativeProps is the React Native equivalent to setting properties directly on a DOM node.
Use setNativeProps when frequent re-rendering creates a performance bottleneck.

Direct manipulation will not be a tool that you reach for frequently; you will typically only be using it for creating continuous animations to avoid the overhead of rendering the component hierarchy and reconciling many views. setNativeProps is imperative and stores state in the native layer (DOM, UIView, etc.) and not within your React components, which makes your code more difficult to reason about. Before you use it, try to solve your problem with setState and shouldComponentUpdate.

24. How to make your React Native app feel smooth on animations ?

The primary reason and an important one why well-built native apps feel so smooth are by avoiding expensive operations during interactions and animations. React Native has a  limitation that there is only a single JS execution thread, but you can use InteractionManager to make sure long-running work is scheduled to start after any interactions/animations have completed.

Applications can schedule tasks to run after interactions with the following:

InteractionManager.runAfterInteractions(() => { // ...long-running synchronous task...});