React Native

React Native Interview Questions

Explain React Native?

React Native is an open-source JavaScript framework introduced by Facebook. It is used for developing a real, native mobile application for iOS and Android platforms. It uses only JavaScript to build a mobile app. It is like React, which uses native components rather than using web components as building blocks. It is cross-platform, which allows you to write code once and can run on any platform.

React Native application is based on React, a JavaScript library developed by Facebook and XML-Esque markup (JSX) for creating the user interface. It targets the mobile platform rather than the browser. It saves your development time as it allows you to build apps by using a single language JavaScript for both Android and iOS platforms.

What are the advantages of React Native?

React Native provides many advantages for building mobile applications. Some of the essential benefits of using React Native are given below:

  • Cross-Platform: It offers the facility to “Write once and run everywhere.” It is used to create apps for Android, iOS, and Windows platforms.
  • Performance: The code written in React Native is compiled into native code, which enables it for all operating systems to provide closer native appearance and functions in the same way on all platforms.
  • Community: React Native provides a large community of passionate developers who are always ready to help us to fix bugs, and issues occur at any instant.
  • Hot Reloading: Making a few changes in your app’s code immediately visible during development. If the business logic is changed, its reflection is live reloaded on screen.
  • Faster Development: React Native helps to develop apps fast. It uses a common language to build an app for Android, iOS, and Windows platforms, which gives speedier app deployment, delivery, and quicker time-to-market.
  • JavaScript: JavaScript knowledge is used to build native mobile apps.

What are the disadvantages of React Native?

Some of the big disadvantages of React Native for building mobile applications are given below:

  • React Native is still new and immature: React Native is a new framework in Windows, Android, and iOS programming languages. It is still in the improvement stage, which can have a negative impact on the apps.
  • Learning is tough: React Native cannot learn quickly, especially for a fresher in the app development field.
  • It Lacks the Security Robustness: React Native is an open-source JavaScript framework, which is fragile and creates a gap in the security robustness. When you are creating banking and financial apps where data is highly confidential, experts advise not to choose React Native.
  • It Takes More Time to Initialize: React Native takes a lot of time for initializing the runtime even if you are using the hi-tech gadgets and devices.
  • Existence is Uncertain: As Facebook develop this framework, its presence is uncertain since it keeps all the rights to kill off the project anytime. As the popularity of React Native rises, it is unlikely to happen.

What is JSX?

JSX is a syntax notation for JavaScript XML(XML-like syntax extension to ECMAScript). It stands for JavaScript XML. It provides expressiveness of JavaScript along with HTML like template syntax. For example, the below text inside h1 tag return as javascript function to the render function.

 render(){
        return(
         <div>
            <h1> Welcome to React world!!</h1>
         </div>
        );
     }

What are components?

Components are the building blocks of any React app and a typical React app will have many of these. Simply put, a component is a JavaScript class or function that optionally accepts inputs i.e. properties(props) and returns a React element that describes how a section of the UI (User Interface) should appear.

const Greeting = () => <h1>Hello World today!</h1>;

This is a functional component (called Greeting) written using ES6’s arrow function syntax that takes no props and returns an H1 tag with the text “Hello World today!”

How to install React Native App in ios?

To install React Native, we will have to follow these steps:

  • Start with installing node and watchman
  • Then, install React native CLI with npm
  • Install Xcode and its Command-line tools
  • Create a React Native project by using the following command
  • React-native init MyNewProject
  • cd MyNewProject
  • react-native run-ios

List the essential components of React Native.

React native have the following core components: Basic UI components in React Native

  • View: View in React Native is equivalent to tag in HTML. It is a content area where the actual UI components (Text, Image, TextInput, etc) would be displayed. View is used to organize the content in a good manner
  • Text: Text is a very basic built-in Component which displays text in the Application
  • Image: A component for displaying images
  • TextInput: This component is used to take user input into the App
  • ScrollView: It is a scrolling container that can host multiple components and views that can be scrolled
  • StyleSheet: Similar to CSS stylesheets, Provides an abstraction layer similar to CSS stylesheet.

User Interface Components in React Native:

  • Button: A basic button component for handling touches that should render nicely on any platform
  • Switch: Renders a Boolean input
  • Slider: A component used to select a single value from a range of values
  • Picker: Renders the native picker component on iOS and Android

ListView Components in React Native:

  • FlatList: A component for rendering performant scrollable lists
  • SectionList: Like FlatList, but for sectioned lists

Android Specific components in React Native

  • DatePickerAndroid: Opens the standard Android date picker dialog
  • DrawerLayoutAndroid: Renders a DrawerLayout on Android
  • BackHandler: Detect hardware button presses for back navigation
  • ProgressBarAndroid: Renders a ProgressBar on Android
  • ToastAndroid: Create an Android Toast alert
  • ViewPagerAndroid: Container that allows flipping left and right between child views.

How many threads run in React Native?

The React Native app contains the following thread:

  • React Native UI Thread (Main Thread): This thread is used for the layout of the mobile app.
  • React Native JavaScript Thread: It is a thread where our business logic will run. It means JS thread is a place where our JavaScript code is executed.
  • React Native Modules Thread: Sometimes, our app needs access to platform API, which happens as a part of native module thread.
  • React Native Render Thread: This thread is used to generate actual OpenGL commands used to draw the app UI.

What are props in React Native?

Props is the shorthand for Properties in React. They are read-only components which must be kept pure i.e. immutable. They are always passed down from the parent to the child components throughout the application. A child component can never send a prop back to the parent component. This help in maintaining the unidirectional data flow and are generally used to render the dynamically generated data.

Example

Here, we have created a Heading component, with a message prop. The parent class App sends the prop to the child component Heading.

// Parent Component  
export default class App extends Component {  
  render () {  
    return (  
     <View style={{alignItems: 'center' >  
         <Heading message={'Custom Heading for Parent class?}/>  
     </View>  
    )  
  }  
}  
  
// Child component  
export default class Heading extends Component {  
  render () {  
    return (  
      <View style={{alignItems: 'center' >  
        <Text>{this.props.message}</Text>  
      </View>  
    )  
  }  
}  
const styles = StyleSheet.create({    
   welcome: {    
    fontSize: 30,    
  }    
});  
Heading.propTypes = {  
  message: PropTypes.string  
}  
Heading.defaultProps = {  
  message: 'Heading One'  
}  

What are State in React Native?

States are the heart of React components. States are the source of data and must be kept as simple as possible. Basically, states are the objects which determine components rendering and behavior. They are mutable unlike the props and create dynamic and interactive components. They are accessed via this.state().

Example

Here, we are going to create a Text component with state data. The content of the Text component will be updated whenever we click on it. The event onPress calls the setState function, which updates the state with “myState” text.

import React, {Component} from 'react';    
import { Text, View } from 'react-native';    
    
export default class App extends Component {    
    state = {    
        myState: 'This is a text component, created using state data. It will change or updated on clicking it.'    
    }    
    updateState = () => this.setState({myState: 'The state is updated'})    
    render() {    
        return (    
            <View>    
                <Text onPress={this.updateState}> {this.state.myState} </Text>    
            </View>    
        );    
    }    
}    

How to run react native app on Android?

o run React Native in Android, we have to follow these:

  • First, enable the USB Debugging option inside the Developer Options.
  • Plug the device via USB to the development machine.
  • Run adb devices command to check that the device is correctly connected to ADB
  • Now install and launch your app by using the below-given command.
  • $ react-native run-android

List Step to Create and start a React Native App?

The following steps are necessary to create and start a React Native app:

Step-1: Install Node.js

Step-2: Install react-native environments by using the following command.

$ npm install -g create-react-native-app
Step-3: Create a project by using the following command.

$ create-react-native-app MyProject
Step-4: Next, navigate in your project by using the following command.

$ cd MyProject
Step-5: Now, run the following command to start the project.

$ npm start

Are all React components usable in React Native?

Web React components use DOM elements to display (ex. div, h1, table, etc.), but React Native does not support these. We will need to find libraries/components made specifically for React Native. But today React is focusing on components that can be shared between the web version of React and React Native. This concept has been formalized since React v0.14.

How Virtual DOM works in React Native?

A virtual DOM is a lightweight JavaScript object which originally is just the copy of the real DOM. It is a node tree that lists the elements, their attributes and content as Objects and their properties. React’s render function creates a node tree out of the React components. It then updates this tree in response to the mutations in the data model which is caused by various actions done by the user or by the system.

This Virtual DOM works in three simple steps.

  • Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.
  • Then the difference between the previous DOM representation and the new one is calculated.
  • Once the calculations are done, the real DOM will be updated with only the things that have actually changed.

Do we use the same code base for Android and iOS?

Yes, we can use the same codebase for Android and iOS, and React takes care of all the native component translations. For example, a React Native ScrollView use ScrollView on Android and UiScrollView on iOS.

Can we combine native iOS or Android code in React Native?

Yes, we can combine the native iOS or Android code with React Native. It can combine the components written in Objective-C, Java, and Shift.

When would you use ScrollView over FlatList or vice-versa?

  • Do you need to render a list of similar items from an array or the data is very big? Use FlatList
  • Do you need to render generic content in a scrollable container and the data is small? Use ScrollView

How do you dismiss the keyboard in react native?

Use built-in Keyboard Module:

import { Keyboard } from ‘react-native’;

Keyboard.dismiss();

What is AppRegistry? Why is it required early in “require” sequence?

AppRegistry is the JS entry point to running all React Native apps. App root components should register themselves with AppRegistry.registerComponent, then the native system can load the bundle for the app and then actually run the app when it’s ready by invoking AppRegistry.runApplication.

import { Text, AppRegistry } from 'react-native';

const App = (props) => (
  <View>
    <Text>App1</Text>
  </View>
);

AppRegistry.registerComponent('Appname', () => App);

To “stop” an application when a view should be destroyed, call AppRegistry.unmountApplicationComponentAtRootTag with the tag that was passed into runApplication. These should always be used as a pair.

AppRegistry should be required early in the require sequence to make sure the JS execution environment is setup before other modules are required.

Explain the use of Flexbox in React Native?

Flexbox is designed to provide a consistent layout on different screen sizes. It offers three main properties:

  • flexDirection
  • justifyContent
  • alignItems

Differentiate between Real DOM and Virtual DOM.

Real DOMVirtual  DOM
1. It updates slow.1. It updates faster.
2. Can directly update HTML.2. Can’t directly update HTML.
3. Creates a new DOM if element updates.3. Updates the JSX if element updates.
4. DOM manipulation is very expensive.4. DOM manipulation is very easy.
5. Too much of memory wastage.5. No memory wastage.

What is the difference between React and React Native?

The essential differences between React and React Native are:

  • React is a JavaScript library, whereas React Native is a JavaScript framework based on React.
  • Tags can be used differently in both platforms.
  • React is used for developing UI and Web applications, whereas React Native can be used to create cross-platform mobile apps.

Which language is used in React Native?

Javascript with ES6 syntax support. If you are from android or ios development background, it’s an advantage

What are the differences between Class and Functional Component?

The essential differences between the class component and functional component are:

Syntax: The declaration of both components is different. A functional component takes props, and returns React element, whereas the class components require to extend from React.

//Functional Component  
function WelcomeMessage(props) {    
  return <h1>Welcome to the , {props.name}</h1>;    
}   
  
//Class Component  
class MyComponent extends React.Component {    
  render() {    
    return (    
      <div>This is main component.</div>    
    );    
  }    
}    

State: The class component has a state while the functional component is stateless.

Lifecycle: The class component has a lifecycle, while the functional component does not have a lifecycle.

How React Native handle different screen sizes?

React Native provides many ways to handle screen sizes. Some of them are given below:

  1. Flexbox: It is used to provide a consistent layout on different screen sizes. It has three main properties:
  • flexDirection
  • justifyContent
  • alignItems
  1. Pixel Ratio: It is used to get access to the device pixel density by using the PixelRatio class. We will get a higher resolution image if we are on a high pixel density device.
  2. Dimensions: It is used to handle different screen sizes and style the page precisely. It needs to write the code only once for working on any device.
  3. AspectRatio: It is used to set the height or vice versa. The aspectRatio is present only in React-Native, not a CSS standard.
  4. ScrollView: It is a scrolling container which contains multiple components and view. The scrollable items can be scroll both vertically and horizontally.

When would you prefer a class component over functional components?

We prefer class component when the component has a state and lifecycle; otherwise, the functional component should be used.

How do you re-render a FlatList?

By using extraData property on the FlatList component.

 <FlatList
    data={data }
    style={FlatListstyles}
    extraData={this.state}
    renderItem={this._renderItem}
/>

By passing extraData={this.state} to FlatList we make sure FlatList will re-render itself when the state.selected changes. Without setting this prop, FlatList would not know it needs to re-render any items because it is also a PureComponent and the prop comparison will not show any changes.

What is “autolinking” in react-native?

React Native libraries often come with platform-specific (native) code. Autolinking is a mechanism that allows your project to discover and use this code.

Autolinking is a replacement for react-native link. If you have been using React Native before version 0.60, please unlink native dependencies if you have any from a previous install.

Each platform defines its own platforms configuration. It instructs the CLI on how to find information about native dependencies. This information is exposed through the config command in a JSON format. It’s then used by the scripts run by the platform’s build tools. Each script applies the logic to link native dependencies specific to its platform.

What is AsyncStorage and how do you use it?

  • AsyncStorage is a simple, asynchronous key-value pair used in React Native applications.
  • It is a local only storage.
  • It comes in two parts: core and storage backend.
    • Core is a consumer of the storage, provides you a unified API to save and read data.
    • Storage backend implements an interface that core API understands and uses. Its functionality depends on storage itself.

What is the significance of keys in React?

Keys are used for identifying unique Virtual DOM Elements with their corresponding data driving the UI. They help React to optimize the rendering by recycling all the existing elements in the DOM. These keys must be a unique number or string, using which React just reorders the elements instead of re-rendering them. This leads to an increase in the application’s performance.

Differentiate between the React component and the React element.

React Element – It is a simple object that describes a DOM node and its attributes or properties you can say. It is an immutable description object and you can not apply any methods on it.Eg –
<button class=”blue”></button>
React Component – It is a function or class that accepts an input and returns a React element. It has to keep references to its DOM nodes and to the instances of the child components.

const SignIn = () => (
  <div>   <p>Sign In</p>   <button>Continue</button>   <button color='blue'>Cancel</button>  </div>);

What is InteractionManager and what is its importance?

InteractionManager is a native module in React native that defers the execution of a function until an “interaction” finished.
Importance: React Native has JavaScript UI thread as the only thread for making UI updates that can be overloaded and drop frames. In that case, InteractionManager helps by ensuring that the function is only executed after the animations occurred.

Describe HOC.

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.

How is data loaded on the server by React Native?

React Native uses Fetch API to fetched data for networking needs.

What is meant by Gesture Responder System?

It is an internal system of React Native, which is responsible for managing the lifecycle of gestures in the system. React Native provides several different types of gestures to the users, such as tapping, sliding, swiping, and zooming. The responder system negotiates these touch interactions. Usually, it is used with Animated API. Also, it is advised that they never create irreversible gestures.

How to use Axios in the React Native?

Axios is a popular library for making HTTP requests from the browser. It allows us to make GET, POST, PUT, and DELETE requests from the browser. Therefore, React Native uses Axios to make requests to an API, return data from the API, and then perform actions with that data in our React Native app. We can use Axios by adding the Axios plugin to our project using the following command.

# Yarn  
$ yarn add axios  
  
# npm  
$ npm install axios --save  

Axios have several features, which are listed below:

  • It makes XMLHttpRequests from the browser.
  • It makes Http requests from the React Native framework.
  • It supports most of the React Native API.
  • It offers a client-side feature that protects the application from XSRF.
  • It automatically transforms response and request data with the browser.

What are refs in React? When to use Refs?

Refs are escape hatch that provides a direct way to access DOM nodes or React elements created in the render method. Refs get in use when:

  • To manage focus, text selection, or media playback
  • To trigger imperative animations
  • To integrate with third-party DOM libraries

What are animations in React Native?

The animation is a method in which images are manipulated to appear as moving objects. React Native animations allows you to add extra effects, which provide great user experience in the app. We can use it with React Native API, Animated.parallel, Animated.decay, and Animated.stagger.

React Native has two types of animation, which are given below.

  • Animated: This API is used to control specific values. It has a start and stops methods for controlling the time-based animation execution.
  • LayoutAnimated: This API is used to animate the global layout transactions.

What do you understand from “In React, everything is a component.”

Components are the building blocks of a React application’s UI. These components split up the entire UI into small independent and reusable pieces. Then it renders each of these components independent of each other without affecting the rest of the UI.

Explain the lifecycle methods of React components in detail.

Some of the most important lifecycle methods are:

  • componentWillMount() – Executed just before rendering takes place both on the client as well as server-side.
  • componentDidMount() – Executed on the client side only after the first render.
  • componentWillReceiveProps() – Invoked as soon as the props are received from the parent class and before another render is called.
  • shouldComponentUpdate() – Returns true or false value based on certain conditions. If you want your component to update, return true else return false. By default, it returns false.
  • componentWillUpdate() – Called just before rendering takes place in the DOM.
  • componentDidUpdate() – Called immediately after rendering takes place.
  • componentWillUnmount() – Called after the component is unmounted from the DOM. It is used to clear up the memory spaces.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button