DEV Community

Cover image for Top React-Native Interview Questions & Answers
Ravi Sharma
Ravi Sharma

Posted on • Updated on

Top React-Native Interview Questions & Answers

Full Setup To Run React Native App On Mac System
https://youtu.be/rTwE7fR7ewI

Top React-Native Interview Questions & Answers

Q.1 What is React Native?

It's an open-source framework developed by Facebook which enables the developer to build cross-platform mobile applications using javascript, which can run natively on both Android and IOS
It uses the same building blocks as a native app built with objective-c/java/swift.

Q.2 Is React Native single-threaded?

Javascript is single-threaded. Since React Native is essentially javascript, It is also single-threaded. In its rendering process, rather than have multiple processes occur at the same time (multithreading), other components have to wait when one component is being rendered.

Q.3 Difference between ReactJS and React-native?

  • ReactJs is a Javascript library for web development while React Native is a framework for mobile development.
  • ReactJs uses web component while React Native uses the native components.
  • With ReactJS you probably will choose a bundler like webpack or other. React Native comes with a metro-bundler that bundle your javascript code into a single file min.bundle.js
  • ReactJs uses Virtual DOM for UI related calculation while in React Native shadow thread performs UI related calculation.

Q.4 What is JSX?

JSX stands for JavaScript XML. It's a templating language for writing XML tags with javascript. We need to import React to be able to use JSX which then be transformed into the native components of each platform.
JSX is used as some kind of wrapper for the underlying components that the OS provides. So you are writing JSX to compose your UI using like components.

Q.5 What is the limitation of React Native

  • It doesn't support all the native APIs.
  • Dependable on third-party libraries.
  • Poor memory management.

Q.6 What is the state in React Native?

State is a type of data, that keeps track of information. A State should be initialized in the constructor. It is mutable so We can update its value inside the component only. It can't be accessed & modified outside the component.
Whenever state value updated (this.setState() called), It marks the component as dirty which means it needs to be re-rendered.

Q.7 What is Props?

Props are the parameters that are used to customize a component at the time of creation and on re-render.
Props are like (key/value pairs) arguments passed to a component from the parent and by passing different values of props, one component can show different UI & different functionality.
A component should not change it's own props, only react to changes of props from the parent component. It is immutable and can't be changed.

Q.8 What is default props?

Default props allow you to set default props value for your component. If you 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 Demo extends Component {
    render() {
        return ( 
            <View>
              <Text> 
               {this.props.name} 
             </Text> 
           </View>
        )
    }
}
Demo.defaultProps = {
    name: 'Jay'
}

export default Demo;
Enter fullscreen mode Exit fullscreen mode

Q.9 What is the use of super() inside the constructor of the component?

A child class constructor can't make use of this reference until super() method has been called.
The main reason for passing props parameter to super(props) call is to access this.props in your child constructors.

constructor(props) {
    super();
    console.log(this.props);  // output- undefined
}

render() {
    console.log(this.props);   // output- porps value which passed.
    return ( 
        <Text> Welcome </Text>
    )
}
Enter fullscreen mode Exit fullscreen mode

Q.10 What are the component lifecycle methods in React Native?

Component Lifecycle divided into three-phase mounting phase, update phase, and unmounting phase.

Mounting Phase- An instance of a component is being created.

  • constructor()
  • getDerivedStateFromProps()
  • render()
  • componentDidMount()

Updating Phase- To update the value of Props or State to React Native.

  • getDerivedStateFromProps()
  • shouldComponenUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

Unmounting Phase- The component is not needed and gets unmounted.

  • componentWillUnmount()

Q.11 Explain the React Native Threads?

There are 3 Threads in React Native:

  • UI Thread- Also known as Main thread. It's main application thread on which your Android/IOS app is running. It has access to UI and your UI can be changed only by this thread.
  • JS Thread- Javascript thread deals with the business logic of the application, where JS code is executed, API calls are made, touch events are processed.
  • Shadow Thread- This thread is the background thread used by React Native to calculate your layout created using the React library.

Q.12 Why we import React in React Native components?

To use JSX in our component we need to import React. Also class component uses overided method render() to return the react-native elements. To use render() method we need to extend Component class provided by React.

Q.13 How React Native works?

When we run 'react-native run-ios' at this point React Native CLI would call metro-bundler that would bundle the JS code into a single file min.bundle.js

  • Now whenever the React Native app starts, the main thread starts execution & starts the loading of the Javascript bundle.
  • When JS code has been loaded successfully main thread sends it to another thread(JS Thread) to keep the main thread response which is responsible for the UI.(Having a separate thread for JavaScript is a good idea because when JS does some heavy calculations freezing the thread for a while, the UI thread will not suffer.)
  • When React Native start rendering Reconciler starts "diffing", and when it generates a new layout(Virtual DOM) it sends changes to another thread(Shadow thread).
  • RN uses the Shadow Thread ("shadow" because it generates shadow nodes) which essentially constructs a tree of your layout you coded in your JS thread. In this thread, RN uses a layout engine called Yoga which converts the flexbox-based layout into a layout system that your native host can understand and then sends layout parameters/objects to the main(UI) thread.
  • Since only the main thread is able to render something on the screen, shadow thread should send the generated layout to the main thread, and only then UI renders.

Q.14 What is React Native bridge?

React Native bridge is a C++/Java bridge which is responsible for communication between the native and javascript thread.

Bridge is a concept that provides a way for bidirectional and asynchronous communication between JS thread and native module.

It works as a transport layer that transports asynchronous serialized batched response message from JS to the native module. Also, communication between JS thread and Shadow thread is done by the react-native bridge.

Q.15 Use of shouldComponenUpdate() methods?

shouldComponenUpdate() method returns a boolean value, whether we need to re-render the component or not, based on the changes occurred in the props.
This method only exists for performance optimization.

Q.16 What are class component and functional components?

Class component uses class keyword of ES6 to create a component and extend the Component class of React. (It's an instance of a class derived from React.Component class). Also, class component override render() method of component class that returns react element. We can use all component lifecycle methods in it.

import React,{Component} from 'react';
import {View, Text} from 'react-native';
class classComponentDemo extends Component {
    render() {
        return ( 
            <View>
              <Text> Hello World </Text> 
            </View>
        )
    }
}
export default classComponentDemo; 
Enter fullscreen mode Exit fullscreen mode

Functional component is just plain javascript function that returns react element(JSX). A functional component is a very light weighted component.
We can use state, and component lifecycle methods in it using react hooks only.

import React from 'react';
import {View, Text} from 'react-native';
FunctionalComponentDemo = (props) => {
        return ( 
            <View>
              <Text> Hello World </Text> 
            </View>
        )
}
export default FunctionalComponentDemo;
Enter fullscreen mode Exit fullscreen mode

Q.17 What is PureComponent and React.memo?

PureComponent is the same as component except that it handles the shouldComponentUpdate() method for us. In class component, we use it by extends PureComponent. When props or state value changes PureComponent will do a shallow comparison on both props and state. It avoids unnecessary re-rendering of the component.

In functional components to avoid unnecessary re-rendering, we use React.memo.

For an example:

import React from 'react';

const DemoApp = (props) => {
  return (
    <View>
      <Demo1 propA={props.propA} />
      <Demo2 propB={props.propB} />
    </View>
  )
}

const Demo1 = (props) => {
  return (
    <Text>{this.props.propsA}</Text>
  )
}

const Demo2 = (props) => {
  return (
    <Text>{this.props.propsB}</Text>
  )
}
Enter fullscreen mode Exit fullscreen mode

In the above example if props.propA changes then Demo1 will re-render but along with Demo2 will also re-render. Because DemoApp is actually re-evaluated and Demo2 is there. So even though its (Demo2) own props didn't change its parent component causes it to re-render.
Therefore we use React.memo with these functional components to avoid re-rendering.

import React, {memo} from 'react';

const Demo1 = memo(props) => {
  return (
    <Text>{this.props.propsA}</Text>
  )
}

const Demo2 = memo(props) => {
  return (
    <Text>{this.props.propsB}</Text>
  )
}
Enter fullscreen mode Exit fullscreen mode

Q.18 Difference between Stateless vs Stateful component?

Stateless component is also known as a Dumb component and don't have any local state. They not connected with the redux store. But these components are memory efficient.(The behavior of these components is independent on its state.)

Stateful component is also known as a Smart component. The behavior of these components is dependent on its state. They are connected with the redux store.

Q.19 Can we use setState() inside componentDidMount?

Just after render() is finished the component is mounted and the componentDidMount() method is called. It's recommended to use async calls for component initialization or an external API call in componentDidMount() method.
Since setState() method is asynchronous we should write it inside componentDidMount().

Q.20 Difference between setState() vs forceUpdate()?

setState() method is typically used to update the component state with one or more state properties. It tells React Native that this component and its children need to be re-rendered with the updated state.

forceUpdate() method is just a way to force a component to re-render. If our render method depends on some other data, we can tell RN that the component needs re-rendering by calling forceUpdate() method.

Q.21 What is Flexbox?

Flexbox is an algorithm & It is designed to provide a consistent layout on different screen sizes. Flexbox specifies the layout of its children( providing the arrangement of elements on the screen). By default, Flexbox arranges its children in a column.

It provides 3 main properties to achieve the desired layout.

  • flexDirection- used to align its elements vertically or horizontally. (It may have values row or column) By default value is column.
  • justifyContent- Used to distribute the elements inside the container. (It may have values center, flex-start, flex-end, space-between, space-around, space-evenly)
  • alignItem- Used to distribute the elements inside the container along the secondary axis(Opposite to flexDirection).(It may have values flex-start, flex-end, stretched)

By Default- main axis-> Vertical axis
By Default- cross axis-> Horizontal axis

Since justifyContent works based on main axis, It will align Items vertically.
& alignItem works based on cross axis, It will align items horizontally.

If we set {flexDirection: 'row'} then the main axis will become the horizontal axis and cross axis will become vertical axis.

Q.22 How to handle element size in React Native?

In mobile development we have to support different screen size. So we can use Dimensions component of react-native to get the height and width of the device.

import {Dimensions} from 'react-native';
 CONST width= Dimensions.get('window').width;
 CONST height= Dimensions.get('window').height;
Enter fullscreen mode Exit fullscreen mode

Q.23 How to use onPress function in React Native View?

For the RN version > 0.55.3 we can add onPress kind of functionality to any View component using onStartShouldSetResponder props.

import React from 'react';
import { View, Text } from 'react-native';
const DemoApp = () => (
  <View onStartSetResponder={() => Alert.alert('Hey')}>
    <Text>Hello World</Text>
  </View>
)
export default DemoApp;
Enter fullscreen mode Exit fullscreen mode

Q.24 How we can disable or set the orientation of app?

Mobile device always has two modes Portrait mode and Landscape mode. Portrait mode is by default mode. When we rotate the device it turns into Landscape mode.

To disable rotation on the android device add below code in the AndroidManifest.xml file:
<activity android: screenOrientation = 'portrait'

On IOS open project in xcode:
Goto-> General->DeploymentInfo & select the portrait mode only.

again re-build the project.

Q.25 How to write platform-specific code?

React Native provides a Platform module that 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
});
Enter fullscreen mode Exit fullscreen mode

There are also a Platform.select method available that takes an object containing Platform.OS as keys and return 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',
      },
    }),
  },
});
Enter fullscreen mode Exit fullscreen mode

Q.26 Difference between Scrollview and flatList?

Scrollview is a generic scrolling container which can host multiple components & view that can be scrolled. It will load items immediately after component loading, so all data will mount into RAM. It can be used to render small number of items.

FlatList component renders its children lazily means it renders only those items which are visible on the screen. FlatList mount 10 items by default to the screen. It provides good performance, It is built to render a large list of items.

Q.27 What is the use of SafeAreaView in React Native?

By default when you make a react-native app, you have seen that it renders the content on the status bar too. SafeAreaView just creates proper space and save the content overriding from the safe area. It is compatible with only IOS_v11 or later.

SafeAreaView renders nested content and automatically apply padding to reflect the portion of the view that is not covered by navigation bar, tab-bar.TO use it just wrap your top-level view(App Container) with a SafeAreaView with flex value 1.

Q.28 How to apply a style to a react-native component?

Styles are defined within a JSON object using inline style or using StyleSheet.create() method. Every react-native component like View, Text, Image etc, accept a style prop which is an object of CSS rules.

But always avoid using object literals({}). They don't have a persistent memory space, so your component will need to allocate a new location in memory whenever the component re-rendered, therefore avoid to use inline styling. Using PureComponent or memo won't even prevent re-renders of object literals. It can be fixed by naming the object outside of the component body.

StyleSheet is a react-native module that allows developers to create immutable stylesheet references. It has StyleSheet.create({}) method that takes an argument of natural style object, which will freeze the object and assign each with an ID. It avoids creating a new style object every render pass.

Q.29 What are the controlled component and uncontrolled component?

Controlled component is the one that takes its current value through props and notifies to parent component about changes in it through a callback. The parent component controls it by handling the callback and managing its own state and passing the new value as props to the controlled component.
For example, TextInput, Slider, Switch, Picker are the controlled components.

Uncontrolled component is one that maintains its own state internally and will be updated when the input value changes. To write an uncontrolled component, there is no need to write an event handler for every state update.

Q.30 What are Hooks?

React 16.8 has included a new feature called 'React Hook'. Hooks are the functions that allow you to use react state & component lifecycle methods in a functional component without converting it into a class component. Hooks do not work with the class components.

Q.31 What is the use of watchman in react native?

Watchman is an open-source project developed by Facebook. It watches files & keeps track of changes in files. It can also trigger action based on file changes.

React Native uses watchman to provide hot reloading feature of react-native. It helps the developer to build application faster. If the developer makes any change in the project file, the watchman will detect the changes and invoke the build to reflect the changes automatically without any developer intervention.

Q.32 What is Fragment?

Fragment is a React feature but we can use it in react native also. Fragment lets you group a list of children without adding an extra node(like View). (It works as a container for other child components). We can use shorter syntax for Fragment like <> & </>.

import React, { Component, Fragment } from 'react';
class FragmentDemo extends Component {
    render() {
        return (
            <Fragement>
                <View></View>
                <ChildComponentA />
                <ChildComponentB />
            </Fragement>
        )
    }
}
export const FragmentDemo; 
Enter fullscreen mode Exit fullscreen mode

Q.33 What is React Native Modal?

The Modal component is a basic way to present content above an enclosing view.
Modal contains its own view which is visible by default. Its has props (animationType, visible, transparent, onRequestClose).

Q.33 What is the use of WebView in React Native?

WebView is a react-native component to render the web pages in your mobile app.
It works as a container for web pages and used to load web content in native view. It is placed in react-native-webview. It has props source, in which we are passing object that contains Html content, or URI.

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { WebView } from 'react-native-webview';
class MyWebComponent extends Component {
  render() {
    return <WebView source={ { uri: 'https://reactnative.dev/' } } />;
  }
}
export default MyWebComponent; 
Enter fullscreen mode Exit fullscreen mode

Q.34 How to use the environment variable in React Native?

We can save environment variable or API keys or any sensitive information inside the .env file. To use this file in our react native app we need to insall library react-native-dotenv. This module lets you import environment variables from .env file.

Q.35 What is AppRegistry?

AppRegistry is the javascript entry point to running all react-native apps.
App root component should register themselves with AppRegistry.registerComponent(). Then the native system can load the bundle for the app & then actually run the app when it's ready by invoking AppRegistry.runApplication().

To stop an application when a view should be destroyed, call AppRegistry.unmountApplicationComponentAtRootTag with the tag that was passed into runApplication.

Q.36 What is Yoga in React Native?

Yoga is a cross-platform layout engine, Yoga has unlocked exciting features such as calculating layouts off of the main thread to help ensure smooth UI performance.

React Native uses the shadow thread which essentially constructs a tree of your layout you coded in your JS thread. In this shadow thread, RN uses layout engine Yoga which converts flexbox based layout into a layout system that your native host can understand.

Q.37 What is Native Module?

A Native module is a set of Javascript functions that are implemented natively for each platform using native languages (Objective C, Swift, Android).

It is used in cases where native capabilities are needed, that react-native doesn't have a corresponding module yet or when the native performance is better.

Q.38 How to implement multilanguage support in react native?

Localization is the process of making something local in characters or restricting it to a particular place. To implement React Native localization and internationalization, we can use third-party npm libraries like (react-native-localize, i18n-js).

*I18n-js * is a small library to provide the I18n translations on the Javascript. Internationalization (I18n) makes it simpler to translate our React Native app into multiple languages. React Native Localization and Internationalization

Q.39 What is the use of Info.plist File?

A property list is basically a dictionary of keys and values that can be stored in your file system with a .plist file extension. The system uses these keys and values to obtain information about your app and how it is configured

An information property list file is a structured text file that contains essential configuration information for a bundled executable. The file itself is typically encoded using the Unicode UTF-8 encoding and the contents are structured using XML.

Q.40 How to handle app state without Redux?

First way-> We can set Global state in our top-level component & function to update those state. Then this global state and function can be passed as props to child components using props drilling. (in which props are passed down multiple levels in a react native component hierarchy).

React Context API-> To avoid prop drilling then we can use react's context API. Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Top comments (2)

Collapse
 
metruzanca profile image
Samuele Zanca

Q.3 Difference between ReactJS and React-native?

ReactJs uses web component while React Native uses the native components.

This is incorrect, react does not use web components. reactjs.org/docs/web-components.html

Collapse
 
metruzanca profile image
Samuele Zanca

You could also say that React Native uses Reactjs internally as part of your answer.