Introduction
React Native (also known as RN) is a popular JavaScript-based mobile app framework that allows you to build natively-rendered mobile apps for iOS and Android. The framework lets you create an application for various platforms by using the same codebase.
React Native was first released by Facebook as an open-source project in 2015. In just a couple of years, it became one of the top solutions used for mobile development. React Native development is used to power some of the world’s leading mobile apps, including Instagram, Facebook, and Skype. We discuss these and other examples of React Native-powered apps further in this post.
There are several reasons behind React Native’s global success.
Firstly, by using React Native, companies can create code just once and use it to power both their iOS and Android apps. This translates to huge time and resource savings.
Secondly, React Native was built based on React – a JavaScript library, which was already hugely popular when the mobile framework was released. We discuss the differences between React and React Native in detail further in this section.
Thirdly, the framework empowered frontend developers, who could previously only work with web-based technologies, to create robust, production-ready apps for mobile platforms.
Interestingly, as with many revolutionary inventions, React Native was developed as a response to…a big technological mistake.
Dive into the world of React Native with our curated collection of Basic React Native Interview Questions & Answers. Whether you’re a beginner exploring the fundamentals or an experienced developer preparing for an interview, this resource provides a comprehensive overview of key concepts in React Native development.
Basic React Native Interview Questions
1. How Different is React-native from ReactJS ?
- Usage Scope
ReactJs – Reactis a JavaScript library for building Responsive User Interfaces for Building Web Application.
React Native – It is a framework for creating mobile applications with a native feel. - Syntax
Both React and React Native uses JSX (JavaScript XML) syntax but React uses html tags like <div> <h1> <p> etc while React Native uses <view> <text> etc. - Animation And Gestures
React uses CSS animations on a major scale to achieve animations for a web page while The recommended way to animate a component is to use the Animated API provided by React-Native. - Routing Mechanism
React uses a react-router for routing and does not have any inbuilt routing capabilities but React Native has a built-in Navigator library for navigating mobile applications.
REACT JS | REACT NATIVE |
It is used for developing web applications. | It is used for developing mobile applications. |
It uses React-router for navigating web pages. | It has a built-in navigator library for navigating mobile applications. |
It uses HTML tags. | It does not use HTML tags. |
It provides high security. | It provides low security in comparison to ReactJS. |
In this, the virtual DOM renders the browser code. | In this, Native uses its API to render code for mobile applications. |
2. 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) |
3. Describe advantages of using React Native ?
There are multiple advantage of using React Native like,
- Large Community
React Native is an Open Source Framework, it is completely community driven so any challenges can be resolved by getting online help from other developers. - Reusability
Code can be written once and can be used for both IOS and ANDROID, which helps in maintaining and as well debugging large complex applications as no separate teams are needed for supporting both the platforms, this also reduces the cost to a major extent. - Live and Hot Reloading
Live reloading reloads or refreshes the entire app when a file changes. For example, if you were four links deep into your navigation and saved a change, live reloading would restart the app and load the app back to the initial route.
Hot reloading only refreshes the files that were changed without losing the state of the app. For example, if you were four links deep into your navigation and saved a change to some styling, the state would not change, but the new styles would appear on the page without having to navigate back to the page you are on because you would still be on the same page. - Additional Third-Party Plugins
If the existing modules do not meet the business requirement in React Native we can also use Third Party plugins which may help to speed up the development process.
4. What are threads in General ? and explain Different Threads in ReactNative with Use of Each ?
The single sequential flow of control within a program can be controlled by a thread.
React Native right now uses 3 threads:
- MAIN/UI Thread— This is the main application thread on which your Android/iOS app is running. The UI of the application can be changed by the Main thread and it has access to it .
- Shadow Thread— layout created using React library in React Native can be calculated by this and it is a background thread.
- JavaScript Thread— The main Javascript code is executed by this thread.
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;
6. 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;
7. 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 .
8. What is Redux in React Native and give important components of Redux used in React Native app ?
Redux is a predictable state container for JavaScript apps. It helps write applications that run in different environments. This means the entire data flow of the app is handled within a single container while persisting previous state.
Actions: are payloads of information that send data from your application to your store. They are the only source of information for the store. This means if any state change is necessary the change required will be dispatched through the actions.
Reducers: “Actions describe the fact that something happened, but don’t specify how the application’s state changes in response. This is the job of reducers.” when an action is dispatched for state change its the reducers duty to make the necessary changes to the state and return the new state of the application.
Store: a store can be created with help of reducers which holds the entire state of the application. The recommended way is to use a single store for the entire application rather than having multiple stores which will violate the use of redux which only has a single store.
Components: this is where the UI of the application is kept.
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
- setTimeout, clearTimeout
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, clearInterval
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.
- setImmediate, clearImmediate
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().
- requestAnimationFrame, cancelAnimationFrame
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. How to debug React Native Applications and Name the Tools used for it ?
In the React Native world, debugging may be done in different ways and with different tools, since React Native is composed of different environments (iOS and Android), which means there’s an assortment of problems and a variety of tools needed for debugging.
- The Developer Menu:Reload:reloads the app
Debug JS Remotely: opens a channel to a JavaScript debugger
Enable Live Reload: makes the app reload automatically on clicking Save
Enable Hot Reloading: watches for changes accrued in a changed file
Toggle Inspector: toggles an inspector interface, which allows us to inspect any UI element on the screen and its properties, and presents an interface that has other tabs like networking, which shows us the HTTP calls, and a tab for performance. - Chrome’s DevTools:Chrome is possibly the first tool to think of for debugging React Native. It’s common to use Chrome’s DevTools to debug web apps, but we can also use them to debug React Native since it’s powered by JavaScript.To use Chrome’s DevTools with React Native, first make sure to connect to the same Wi-Fi, then press command + R if you’re using macOS, or Ctrl + M on Windows/Linux. In the developer menu, choose Debug Js Remotely. This will open the default JS debugger.
- React Developer Tools
For Debugging React Native using React’s Developer Tools, you need to use the desktop app. In can installed it globally or locally in your project by just running the following command:
yarn add react-devtools
Or npm:
npm install react-devtools –saveReact’s Developer Tools may be the best tool for debugging React Native for these two reasons:
It allows for debugging React components.
There is also a possibility to debug styles in React Native. There is also a new version that comes with this feature that also works with the inspector in the developer menu. Previously, it was a problem to write styles and have to wait for the app to reload to see the changes. Now we can debug and implement style properties and see the effect of the change instantly without reloading the app. - React Native Debugger
While using Redux in your React Native app, React Native Debugger is probably the right debugger for you. This is a standalone desktop app that works on macOS, Windows, and Linux. It even integrates both Redux’s DevTools and React’s Developer Tools in one app so you don’t have to work with two separate apps for debugging.
React Native CLI
You can use the React Native CLI to do some debugging as well. It can also be used for showing the logs of the app. Hitting react-native log-android will show you the logs of db logcat on Android, and to view the logs in iOS you can run react-native log-ios, and with console.log you can dispatch logs to the terminal:
console.log("some error🛑")
11. What is Props Drilling and how can we avoid it ?
Props Drilling (Threading) is a concept that refers to the process you pass the data from the parent component to the exact child Component BUT in between, other components owning the props just to pass it down the chain.
Steps to avoid it
- React Context API.
2. Composition
3. Render props
4. HOC
5. Redux or MobX
12. Describing Networking in React Native and how to make AJAX network calls in React Native?
React Native provides the Fetch API for networking needs.
To fetch content from an arbitrary URL, we can pass the URL to fetch:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue'
})
});
Networking is an inherently asynchronous operation. Fetch methods will return a Promise that makes it straightforward to write code that works in an asynchronous manner:
const getMoviesFromApi = () => {
return fetch('https://reactnative.dev/movies.json')
.then((response) => response.json())
.then((json) => {
return json.movies;
})
.catch((error) => {
console.error(error);
});
};
The XMLHttpRequest API is built in to React Native Since frisbee and Axios use XMLHttpRequest we can even use these libraries.
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success', request.responseText);
} else {
console.warn('error');
}
};
request.open('GET', 'https://mywebsite.com/endpoint/');
request.send();
13. 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:
- Set up React Native dependencies and directory structure.
- Develop your React Native components in JavaScript.
- Add a ReactRootView to your Android app. This view will serve as the container for your React Native component.
- Start the React Native server and run your native application.
- Lastly, we need to Verify that the React Native aspect of your application works as expected.
14. How do you install and create a React Native application ?
Before you begin, make sure you have Node.js and NPM installed on your system.
To install a React Native application, you can use the following command:
$ npm install -g create-react-native-app
To create a React Native project, you can use the following command:
$ create-react-native-app AppName
To navigate in your project, use the following command:
$ cd AppName
And to start your project, run this command:
$ npm start
React Native is an open source framework developed by Facebook which enables developers to build cross-platform mobile applications using Javascript. With React Native, one can develop a mobile application by using the same design principles used to develop a web application with ReactJs framework. It allows the developer to build mobile application UI by composing multiple components in a declarative way. Before React native, there were few options like Cordova, ionic available to build a hybrid application.
These applications were written using web technology but the hybrid app was not a native application and lacks performance issue. React native solves those performance issues that is why it quickly became popular in React community. Under the hood, React native bridge invokes the native rendering APIs in Objective-C (for IOS) and Java (for Android). That is why they perform better than hybrid application development frameworks. React native has a very good community of developers who actively contribute to the framework.
JSX is a system used for embedding XML in Javascript. You can say that JSX is a templating language for writing HTML/XML tags with Javascript. With the help of JSX, HTML/XML can be written inside Javascript file. JSX enables conditional rendering of React components. React includes building step which converts JSX into Javascript code which is ultimately executed by browser in case of a web app or react Native in case of React Native. JSX is added to improve the developer experience. ReactJS provides few APIs which make the HTML structure in a browser. Those APIs were a little cumbersome to frequently used. That is why React JS introduced JSX and added a tooling step to convert JSX into platform understandable code. With the help of JSX, we can execute javascript to build HTML tags very easily. Here is an example of a JSX code:
<View style={styles.container}>
<TouchableOpacity onPress={this.decrement}>
<Text style={styles.text}>-</Text>
</TouchableOpacity>
<Text style={styles.text}>{this.state.count}</Text>
<TouchableOpacity onPress={this.increment}>
<Text style={styles.text}>+</Text>
</TouchableOpacity>
</View>
Above JSX code is creating one View component which contains two TouchableOpacity component as its child element. We are accessing Javascript variable in Text component with curly brace.
17. What is the role of hooks in React Native ?
Hooks allow developers to ‘hook into’ existing components and access their state and lifestyle features. Previously, these would not be accessible for use elsewhere. With hooks, developers can now tap into a component’s state and lifestyle features without having to write a new class.
18. What is the role of fast refresh in React Native ?
Fast refresh allows developers to get near-instant feedback on recent changes in their app. Once ‘Enable fast refresh’ in the developer menu is toggled, any new edits in the program become visible within a few seconds for an easy evaluation.
19. How do you import components in React Native ?
In React Native, you can import components from scratch, or also import ready-made ones from another file.
To import a component, you need to type <import { Component } from ‘react-native’>, changing the word in brackets depending on the type of component you want to import.
20. What coding languages are compatible with React Native ?
While React Native is generally used with JavaScript, compatibility with other coding languages, including Python, C++, and C, is also possible through the framework’s Java Native Interface (JNI).
21. What engine does React Native use ?
In React Native, JavaScript code runs through two engines:
- JavaScriptCoreis used on iOS simulators and Android emulators; virtually all operations run through this engine
- V8 is used when Chrome debugging is being performed