React Native Interview Questions

Want to become an expert in cracking React Native interview questions? Start with practising the questions below. Crack your next React Native interview with the frequently asked questions.

  • 4.6 Rating
  • 45 Question(s)
  • 30 Mins of Read
  • 9854 Reader(s)

Intermediate

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. Its code is available on Github and has 70k+ stars.

There are following benefits of using React Native in mobile application development

  1. React Native enables a web developer to build mobile apps with Javascript.
  2. The developer doesn’t need to learn complete new programming language java/ Kotlin to develop Android App. Similarly, the developer doesn’t need to be an expert in objective C or swift to develop IOS app anymore. Javascript is more than sufficient to build a mobile app for both Android and IOS. However, knowing java or swift helps the developer to write performance robust mobile app.
  3. With React Native, most of the code base can be shared between the Android app and the IOS app.
  4. With a single code base, effort in maintenance is reduced by many folds.
  5. With a single code base, features can be shipped much faster on both major mobile platform
  6. Developer having experience with ReactJs can quickly learn React Native. The learning curve for a developer is very low.
  7. App developed with React Native is not a web app running inside a mobile app. It is a real mobile app because it uses the same fundamental building blocks as regular IOS native app and Android app uses.
  8. React Native lets you build an app faster as it’s tool gives hot reloading functionality out of the box which means we don’t need to recompile app again and again on making changes.
  9. React Native gives the flexibility to use Native swift or java module with React Native application. So your app can get the best from both worlds.

Javascript developer always tried to explore platforms where Javascript can be used to build better user experiences. React native is not the first framework which enables web developers to build applications for the mobile platform. Ionic, Cordova were few very popular application framework which was used to develop a mobile application using web technologies. One major motivation towards this effort was having a seamless experience on all the platforms. Mobile application developed with React Native is different than alternate frameworks in the following ways:

  1. React Native app is a real mobile app, not a web app running inside a mobile app shell. Other alternative like Cordova, ionic run a web app in a web view.
  2. React Native app is converted into machine code which runs on mobile that is why it gives better performance than other alternatives.
  3. React Native mobile apps are more close to Native app development in comparison to other Javascript frameworks
  4. Mobile application built with React native has small bundle size in comparison to older hybrid application development framework.

There are many renowned companies developing their mobile app with React Native. Big companies like Facebook, Airbnb, Instagram, Pinterest, Uber, Tesla are a few names whose main consumer-facing mobile app is developed with React Native. This shows their trust in the React native framework. Airbnb was a very early adopter of React native. They actively shared their experience with React native framework. They also open sourced many React native library built on top of React native framework. One of their famous libraries is Lottie which makes complex animations work in React native. Many startups are using React native to build their mobile app using React native. They are able to quickly launch their idea on Android and IOS platform at once. Instagram is also built with React native and able to handle large user interaction. This clearly shows that React native is very mature and robust mobile app development framework available today.

Developer experience is one of the most important attributes of a framework. If getting started step with any framework is very difficult and very complex then the community will take lots of time to accept that framework. That is why React native has tried their best to simplify the getting started step for app development. To build a mobile app with React Native, one should have a good understanding of Javascript concepts and understanding of CSS helps in styling React Native app. React Native provide CLI (command line interface) which is used to bootstrap the mobile application. For IOS development Xcode and for Android app development, Android studio is required. Understanding of component driven development with ReactJs is also very beneficial in React Native app development. There is one more open source project named Expo CLI which provides a command line utility to easily start development of React native. It also provides barcode based approach to share the app within the team. Developer experience is pretty good for React native that is also one of the reasons for its huge popularity in the developer community.

ReactJS and React native, both are developed and open sourced by Facebook Inc. React native framework follows the React JS framework's basic architecture. React native also promotes a component-based approach to build mobile screens. All the React natives possess similar lifecycle methods which are exposed by React js component. But still, there are a few differences between ReactJS and React Native

  1. We use div, span etc. HTML tags to build the UI of the web application but in case of React Native, we use View, Text imported from React Native library.
  2. Since React Native is used to developing for Native platform, we can’t access the browser features like window object, local storage etc…
  3. React JS and React native are two different open source project on Github.
  4. Any new feature related to component architecture first implement by ReactJS and then support is added in React Native framework.
  5. Both have different tooling for getting started with development.

React native comes with static type checking tooling enabled by default but you need to perform few steps to enable flow static type checking in React project.

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.

Long time back, web developer realises that there are few elements which are frequently used in web development like drop down and different type of button. The developer started making CSS frameworks which provide already developed components. Bootstrap was first very popular CSS framework which helped web developer to build user experience very quickly. React also follows the same approach in web development. Component driven development is a methodology where we break the complete UI design into several small reusable components and develop them independently. Then the complete UI is built by composing these small components. This methodology helps us write UI code in a modular way. UI development will be faster as we will be reusing components at multiple places. Less code also results in less effort in maintaining the code and also less number of bugs. So we can say that component driven development was already there in web development but React JS made it very popular in the developer community. New frameworks like Angular4+ are also following the same methodology to develop the web application.

Props are parameters which are used to customise a component at the time of creation and on re-render. Props are like arguments passed to a React component. For example, Image is a very basic component provided by React Native library to display an image. It accepts a prop called source which is used to control what image it shows. By passing different values of props, one component can show different UI and different functionality. So we can say that props help use and reuse the same component at different places. Props are set by the parent component and remain fixed for an entire lifecycle of a component.

import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import Counter from './components/Counter';
import Greeting from "./components/Greeting2";
import SimpleTextInput from './components/SimpleTextInput';
import SimpleButton from './components/SimpleButton';
import LoginForm from './components/LoginForm';
import PictureList from './components/PictureList';

export default class App extends React.Component {
  render() {
    const pictureData = {
      uri: 'https://picsum.photos/300/300'
    };
    return (
      <View style={styles.container}>
        <PictureList />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5fcff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  image: {
    margin: 5,
    borderRadius: 5,
    width: 300,
    height: 300
  }
});

State is another way apart from props by which we can modify a React component. React component’s state value changes in the life cycle of component, unlike props. We should not directly change state value of react component. React framework gives the setState method by which state of a component should be changed.

import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';

class Counter extends React.Component {
    state = { count: 0 };
    increment = () => this.setState({count: this.state.count + 1});
    decrement = () => this.setState({count: this.state.count - 1});
    render() {
        return (
            <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>
        );
    }
};
const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        borderRadius: 5,
        borderWidth: 1,
        borderColor: '#1a91b8',
        padding: 5,
        backgroundColor: '#eaf7fd'
    },
    text: {
        color: '#015169',
        fontWeight: 'bold',
        fontSize: 20,
        padding: 15
    }
});
export default Counter;

Above code is an implementation of a counter component. This component has a state count whose value is changed by clicking on the plus (+) and minus (-) button. As the state count of this component is changing the number displayed on UI is also changing. Whenever we create any component in React, first we divide the screen in the component then decide what state a component should have. The beauty of this component is that it is an independent component and can be used anywhere in the application. That is how we make several fully functional component in React to build the complete application.

Starting a project from scratch is always a little bit harder that is why there are some tooling available which we can use to bootstrap a React Native project.

  • Using react-native-cli (https://www.npmjs.com/package/react-native-cli)
    • react-native-cli created a pure react native application as it doesn’t hide any piece of code in the generated project. You can see ios and android folder in a directory structure. Although, you don’t need to modify anything inside generated ios and android folder, They are required to run React native application successfully on the device.
  • Using expo-cli (https://www.npmjs.com/package/expo-cli)
    • Expo-Cli is a third party tooling which provides base files and easy setup steps to start React Native app development. It also provides barcode based steps to share the app with other team members. The downside of bootstrapping React native app with expo cli is the size of the basic app is considerably big as expo cli includes few expo based libraries with the app.

Watchman is an open source project developed by Facebook. As the name of the software correctly suggests that it watches files and keep track of changes in files. It can also trigger action based on file change. React native uses watchman to provide hot reloading feature of React Native. Hot reloading of React native application helps the developer to build application faster. Native mobile application development doesn’t have this feature which means, a developer has to make changes and compile the project to see an out on the device. But React native saves time by automating this task and provide hot reloading. With React native, if the developer makes any change in the project file, the watchman will detect the change and invoke the build to reflect the changes automatically without any developer intervention. Hot reloading feature of React native make it a developer friendly framework and definitely speed up the development. Installation of the watchman is mentioned in the React native’s environment setup step.ac

Every React Native component like View, Text, Image etc… accepts a style prop which is an object of CSS rules. The only difference between CSS rules and CSS object used in React Native is key in CSS object has CSS rules in camelCase, for example, CSS rule background-colour will become backgroundColour in React Native. There are few restrictions over values of some CSS rules. But still, available CSS rules are enough to style a mobile app UI beautifully. React Native supports CSS flexbox to build UI layouts. We style our mobile screen like below snippet:

const styles = StyleSheet.create({
   container: {
       flexDirection: 'row',
       borderRadius: 5,
       borderWidth: 1,
       borderColor: '#1a91b8',
       padding: 5,
       backgroundColor: '#eaf7fd'
   },
   text: {
       color: '#015169',
       fontWeight: 'bold',
       fontSize: 20,
       padding: 15
   }
});
Then we can use these style with View component like below:
<View style={styles.container}></View>

Stylesheet object is provided by React native library which has the method “create”. It takes an argument of type object and this object is the collection of CSS rules. As you can see in the above example, font-size CSS property in the web becomes font size in React native and flex-direction becomes flexDirection. I hope you got the idea about styling in React native application development. You can find the complete code on https://gist.github.com/PavanKu/98f92103af84faaf540aa348cf1a1126

React native follows the box-model concept of CSS. The size of the element is calculated based on the size of content, padding, border, margin. The simplest way to set the size of an element is to set width and height CSS property for an element. All dimensions in React Native is unitless and represent density-independent pixels. By setting fixed height and width, the element will look exactly the same size on different screen sizes. But there is an instance where you want to give the width and height of an element in percentage. Directly use of percentage is not supported in React native but React native does give a dimension module which can be used to give width in percentage. Dimension module gives the width and height of the mobile device. This information can be used to set the style of an element in runtime. Below is the example of how to use Dimension module from React native:

Importing module from React Native:

import { Dimension } from ‘react-native’;

Figure out width and height of the device:

const deviceWidth = Dimension.get(“window”).width;

const deviceHeight = Dimension.get(“window”).height;

Calculate the style value:

Width: deviceWidth*<percentageValue>/100

But the simplest way is by setting width and height CSS for an element.

By default, View component in React native has the display set to flex. Flex is a CSS property which is used to expand and shrink a component dynamically based on available space. If you set flex:1 then the component will take up all the available space. If a parent element is given flex:1 then all its child elements will evenly distribute available space among themselves. We can change the width of the child element by giving a higher value of flex property. The larger the flex given, the higher the ratio of space a component will take compared to its siblings. A component can only expand to fill the available space if its parent has dimensions greater than 0. To make flex work, the parent element must have some width set to it then only flex property will evenly distribute available space. Otherwise, the element will consider width equal to zero and will not be visible on UI. Along with flex property, alignItems and justify-content CSS properties are also used to design mobile UI.

CSS Flexbox is used to design a responsive layout easily without using float or position CSS property. Float and position values were used to build any type of UI which are not very easy. Flexbox is added in CSS3. Flexbox is designed to provide a consistent layout on different screen sizes. You will normally use a combination of flexDirection, alignItems, and justify-content to achieve the right layout. There are few differences in default values of few flex based CSS properties between React Native and on the browser. The default value of flexDirection is a row in the web but in case of React native, its default value is a column. Also, flex parameter only supports a single number in React native. Flexbox alignItems has few more values like flex-start which start aligning element from start and opposite of this is flex-end which places the first child element at the end. Similar to alignItems, justifyContents also have values which behaves where much similar to flexbox behaviour in a web browser.

JustifyContent property aligns the flexible container's items when the items do not use all available space on the main axis. By default, the main axis is a vertical axis in case of React native. Which means justifyContent property aligns child elements of flex parent vertically in React native.  We can use this property to layout elements in a flex container. JustifyContent supports the following values: flex-start|flex-end|centre|space-between|space-around|initial|inherit; It also apply some control over the alignment of items when they overflow the line. Let me explain JustifyContent’s values:

  • flex-start: this is the default value for justifyContent. It means that flex items will start from the top and evenly distributed vertically.
  • Flex-end: this is just the opposite behaviour of flex-start. Elements start rendering from the bottom
  • Center: Items will be placed in the middle
  • Space-between: elements are evenly distributed along the main axis (vertical axis)
  • Space-around: flex items will be evenly distributed with equal space around them

You can think of alignItems as justifyContent behaviour for cross axis. Cross-axis in case if React native is the horizontal axis. CSS alignItems property sets the alignSelf value on all direct children as a group. In Flexbox, it controls the alignment of items on the cross axis. By default, the cross axis is a horizontal axis in case of React native. We can use this property to layout elements in the flex container. The alignItems property supports following values: stretch|center|flex-start|flex-end|baseline|initial|inherit;  Let me explain alignItems values:

  • flex-start: this is the default value for alignItems. It means that flex items will start from the left and evenly distributed horizontally.
  • Flex-end: this is just the opposite behaviour of flex-start. Elements start rendering from the right and go up to the left end.
  • Center: Items will be placed in the middle
  • Space-between: elements are evenly distributed along the cross axis (horizontal  axis)
  • Space-around: flex items will be evenly distributed with equal space around them

By default, the main axis is the vertical axis and cross axis is the horizontal axis in React native. Since justifyContent and alignItems property works based on the main axis and cross axis, so justifyContent will align flex items vertically and alignItems will layout flex item horizontally. This default value of the main axis and cross axis can be changed by changing flexDirection property. If we set flexDirection to row in the flex container then the main axis will become horizontal axis and cross axis will become vertical axis. On changing default behaviour via flexDirection CSS property, the behaviour of alignItems and justifyContent will also get switched. The Concept of flexDirection is also present on the web. Flexbox is implemented as a single direction layout technique and this direction is managed by flexDirection CSS property. Apart from row and column, the flexDirection property has two more values: row-reverse and column-reverse. As the name suggests, the direction will remain horizontal and vertical but the direction will get changed.

Though most of the CSS properties works in the same way in React native still there are few differences in CSS property values between a browser and React native:

  1. Only two values of CSS property display (none, flex) is supported in React native. display none is used to hide an element.
  2. aspectRatio is non-CSS property supported by React Native. we can use aspect ratio to give a size to an element. if either width or height is specified along with aspect ratio then other parameters will be calculated and applied based on aspect ratio value
  3. marginHorizontal has the same effect as setting both marginLeft and marginRight. Similar to marginHorizontal, marginVertical has the same effect as setting both marginTop and marginBottom.
  4. The default value of the position in React native is relative instead of static. so absolute positioning is always just relative to the parent.

Apart from the above difference, most of the CSS properties work exactly the same as they work in a browser.

here are two ways of writing a react component

  • Functional component
    • It uses a simple function which returns the JSX
  • Class-based component
    • It used the class keyword introduced in ES6. it implements render lifecycle method which returns the JSX.

Example of functional component

Example of class-based component

/* Class based component */
import React, { Component } from 'react';
import { Text } from 'react-native';

export default class Greeting extends Component {
    render() {
        return (
            <Text>Hello {this.props.name} !</Text>
        );
    }
}

/* Functional component */
import React, { Component } from 'react';
import { Text } from 'react-native';

export default function Greeting(props) {
        return (
            <Text>Hello {props.name} !</Text>
        );
}

cases are known as a presentational or dumb component. The functional component gets information via props from its parent component and renders the information. You can see that the functional component accepts props as an argument. ES6 arrow function also is used to define a functional component. The functional component doesn’t store any state and also doesn’t override any lifecycle method of React component. The class-based component has the ability to store state within the component and based on its state value behave differently. The latest version of React 16.8 has included a new feature called React hooks by which we can add state in a functional component.

Though we can implement in both functional and class-based way, there are few fundamental differences between the two of them:

  1. Functional component can’t have stated ( before React hooks era ). It renders component only based on props passed. A class-based component can have a local state which can be helpful in building a bigger component
  2. Functional component access directly via props argument passed. In a class-based component, props are accessible via this.props.
  3. A class-based component is a more complex structure. It is an instance of a class derived from React. Component class. The class must implement a render() member function which returns a React component to be rendered
  4. The class-based component can also use lifecycle methods but functional component can’t use lifecycle methods.
  5. Functional components are a very light weighted component in comparison to class-based react component

Below image summarise the lifecycle methods exposed by react component and the order in which lifecycle methods are being called by React.

React 16 was a major release for ReactJS. With this version react has marked some of the lifecycle methods like componentWillRecieveProps, ComponentWillUpdate as deprecated. In a later release of React, the framework will be removing these methods. In place of deprecated methods, they added a few new lifecycle methods. The above picture shows the lifecycle method of a component. We can divide the lifecycle methods of the component into three categories.

  • Mounting: This includes the beginning phase of the component. The first constructor of the component gets invoked. Constructor receives props as an argument from the parent component. Constructor is the place where we define an initial state of a component. After constructor and before render, lifecycle method getDrivedStateFromProps is invoked, it returns the state object or null to avoid the render. Then Render method is invoked which renders the JSX. Then at the end, componentDidMount is invoked.
  • Updating: A component gets an update via a change in state or change in props. In both of these cases, the getDrivedStateFromProps method is invoked first where we get props and state as an argument and returns updated state. Then shouldComponentUpdate methods are invoked. If this method returns true then the only component gets the update otherwise component update is aborted. Then render method is called and after this getSnapshotBeforeUpdate is called. In the end, the componentDidUpdate method is called
  • Unmounting: componentWillUnmount lifecycle method is invoked before the unmounting of the component takes place.

TextInput is provided by React native framework to implement simple text input control. Text input is one of the very basic controls of UI. Whether it is auto-complete, form, text input is a must used control in UI of application. TextInput component accepts placeholder value as props. When a user starts changing the text then the onChangeText event is triggered and when the user is done editing and hit return button, onSubmitEditing props will get invoked. TextInput component can be styled by setting style props to the component. Here is an example of the implementation of simple text input in React native:

import React from 'react';
import { View, Text, TextInput, StyleSheet } from "react-native";

class SimpleTextInput extends React.Component {
    constructor(props) {
        super(props);
        this.state = { text: '', isSubmitted: false };
    }
    handleChangeText = (text) => {
        this.setState({ text, isSubmitted: false });
    }
    handleSubmitText = () => {
        this.setState({ isSubmitted: true });
    }
    render() {
        const { text, isSubmitted } = this.state;
        return (
            <View style={styles.container}>
                <TextInput
                    style={styles.input}
                    placeholder={'Type here...'}
                    onChangeText={this.handleChangeText}
                    onSubmitEditing={this.handleSubmitText}/>
                <Text style={styles.text}>{isSubmitted?`User has typed: ${text}`:'User is typing'}</Text>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        alignSelf: 'stretch',
        margin: 10,
        padding: 10,
        borderColor: '#ccc',
        borderWidth: 1,
        borderRadius: 5,
        backgroundColor: '#eaf7fd'
    },
    text: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#015169'
    },
    input: {
        height: 40
    }
});

export default SimpleTextInput;

In the above example: we have a TextInput component whose value is controlled by the state. Which means our TextInput in above example is a controlled component. Once the user starts typing we update the state with an onChangeText method. Once the user submits the value, we display the value user has typed in the text box.

React native provides Button component which displays platform specific button. Following example shows how we create a platform-specific default button in React native. Platform-specific button means that the look and feel on a button will depend on whether the application is running on IOS or Android. Button component exposes two main props: title and onPress. Title props are used to display text on the button. onPress props is a callback which is invoked when the user presses the button. This is very much similar to the click event on a web browser. We can’t style the Button component provided by React native.

import React from 'react';
import { View, Alert, Button, StyleSheet } from "react-native";

const SimpleButton = (props) => {
    return ( <Button style={styles.button} onPress={() => Alert.alert("You pressed button")} title="Click Me"/> );
};

const styles = StyleSheet.create({
    button: {
        padding: 5,
        color: '#000'
    }
});

export default SimpleButton;

Above example will show platform specific alert when the user presses the button. Alert is the component provided by React native framework to show platform specific modal. As I mentioned above that we can’t style Button component of React native, we can try this by changing the text colour of a button or changing the padding via style props but it won’t change the appearance of the button.

Advanced

Login functionality is an essential part of any mobile application. We can design a login component which performs a client-side validation and if it passes then make an API call to the server for authentication of the user. We can create a simple login screen using TextInput, View and Button component. Since Button component renders based on the platform, it will give different look and feel on IOS and Android. To avoid this, we can use TouchableOpacity to create a button component. TouchableOpacity component can be styled as per the requirement. Similar to Button component, TouchOpacity component also provides onPress props where we assign our click listener. Following code explains the implementation of a Login form

import React from 'react';
import { View, StyleSheet, Text, TouchableOpacity, TextInput, Alert } from "react-native";
const initialState = { username: '', password: '' };
class LoginForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = initialState;
        this.handleSubmitForm = this.handleSubmitForm.bind(this);
        this.handleUsernameChange = this.handleUsernameChange.bind(this);
        this.handlePasswordChange = this.handlePasswordChange.bind(this);
    }
    handleUsernameChange(text) {
        this.setState({ username: text });
    }
    handlePasswordChange(text) {
        this.setState({ password: text });
    }
    handleSubmitForm() {
        const { username, password } = this.state;
        Alert.alert(`User ${username} is log in with password ${password}`);
    }
    render() {
        return (
            <View style={styles.container}>
                <View>
                    <Text style={styles.text}>Username</Text>
                    <TextInput autoCorrect={false} autoCapitalize={'none'} style={styles.input} onChangeText={this.handleUsernameChange}></TextInput>
                </View>
                <View>
                    <Text style={styles.text}>Password</Text>
                    <TextInput autoCorrect={false} autoCapitalize={'none'} style={styles.input} secureTextEntry onChangeText={this.handlePasswordChange}></TextInput>
                </View>
                <TouchableOpacity style={styles.button} onPress={this.handleSubmitForm}>
                    <Text style={[styles.text, styles.center]}>Login</Text>
                </TouchableOpacity>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        alignSelf: 'stretch',
        margin: 10,
        padding: 10,
        borderColor: '#ccc',
        borderWidth: 1,
        borderRadius: 5,
        backgroundColor: '#fff'
    },
    text: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#015169',
        paddingVertical: 5
    },
    input: {
        height: 40,
        borderColor: "#e0e0e0",
        borderWidth: 1,
        borderRadius: 5,
        marginBottom: 15,
        paddingHorizontal: 10
    },
    button: {
        padding: 10,
        borderColor: '#bee6fe',
        borderWidth: 1,
        borderRadius: 5,
        backgroundColor: '#eaf7fd'
    },
    center: {
        alignSelf: 'center'
    }
});
export default LoginForm;

Username and password TextInputs are controlled component here as its value is getting stored as a state of the component. onPress event of the login button, we validate the user input and if everything looks good then we will make the API call for login. We style this component using Stylesheet. create method. We used normal CSS rules to make this form looks nice.

ScrollView component is a generic scrolling container which can host multiple components and Views. you can scroll both vertically and horizontally (by setting the horizontal property). ScrollView can also be used to implement pinch and zoom functionality in IOS. Swiping horizontally between views can also be implemented on Android using the ViewPagerAndroid component. ScrollView works best to present a small number of things of a limited size. All the elements and views of a ScrollView are rendered, even if they are not currently shown on the screen.

import React from 'react';
import { View, Text, Image, ActivityIndicator, StyleSheet, ScrollView } from "react-native";

const initialState = { pictures: [
{id:0, download_url:"https://picsum.photos/id/0/5616/3744" },
{id:1, download_url: "https://picsum.photos/id/1002/4312/2868"},
{id:2, download_url: "https://picsum.photos/id/1006/3000/2000"},
{id:3, download_url: "https://picsum.photos/id/1015/6000/4000"}
] };
class PictureList extends React.Component {
    constructor(props) {
        super(props);
        this.state = initialState;
    }
   
    render() {
        const { pictures } = this.state;
        if (!pictures.length) { return (<ActivityIndicator />); }
        return (
            <View>
                <ScrollView>
                  {pictures.map(picture => (
                    <View style={styles.container} key={picture.id}>
                        <Image style={styles.image} source={{uri: picture.download_url}} />
                    </View>
                  ))}  
                 />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        borderColor: '#ccc',
        borderWidth: 1,
        borderRadius: 5,
        backgroundColor: '#eaf7fd',
        marginBottom: 15,
    },
    image: {
        margin: 5,
        borderRadius: 5,
        width: 300,
        height: 300,
    }
});

export default PictureList;

Above example renders a list of images in ScrollView. We import the ScrollView component from the react-native library and created Image element inside ScrollView. Each Image element has its own width and height set via CSS. When you run the above code and scrolls the screen you should be able to go through all the images renders. The scroll view is used to create scrollable UI on a mobile application. It works on both IOS and Android.

React native provides FlatList component to display a long line of data. For example, the News app normally displays a list to article summary card on the home page. these list of the card should be implemented using FlatList component. FlatList works well for long lists of data, where the number of items might change over time. Unlike the more generic ScrollView, the FlatList only renders elements that are currently visible on the screen, not all the elements at once. FlatList provides a performance boost over ScrollView as FlatList creates a card at runtime when the user starts scrolling the page. But ScrollView creates all the list item (card) at once.

We can use FlatList or SectionList component to render a list of items on a mobile app. But there are differences between these two components provided by the react-native library. If you want to render a set of data broken into logical sections, maybe with section headers. It takes sections as props whose values is an array of object and each object should have title property. This titled property will be used by SectionList to render the list heading. But FlatList just iterates the list and create a node to render on UI. In case you want to show the header for a group of the list then you need to customize the node and add a header to it. The basic difference is heading for a group of a node is provided out of the box via SectionList component of react-native but with FlatList, we need to implement ourselves.

We can use javascript to develop a mobile application using React native. calling an API is very much similar to how we make AJAX call in web application. Below example explains it in detail.

import React from 'react';
import { View, Text, Image, ActivityIndicator, StyleSheet, FlatList } from "react-native";

const initialState = { pictures: [] }
class PictureList extends React.Component {
    constructor(props) {
        super(props);
        this.state = initialState;
    }
    async fetchPictures() {
        const api = 'https://picsum.photos/v2/list';
        const fetchResponse = await fetch(api);
        const pictures = await fetchResponse.json();
        this.setState({ pictures });
    }
    componentDidMount() {
        this.fetchPictures();
    }
    render() {
        const { pictures } = this.state;
        if (!pictures.length) { return (<ActivityIndicator />); }
        return (
            <View>
                <FlatList data={pictures} renderItem={({item}) => (
                    <View style={styles.container} key={item.id}>
                        <Image style={styles.image} source={{uri: item.download_url}} />
                    </View>
                    )} keyExtractor={(item, id) => item.id}/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        borderColor: '#ccc',
        borderWidth: 1,
        borderRadius: 5,
        backgroundColor: '#eaf7fd',
        marginBottom: 15,
    },
    image: {
        margin: 5,
        borderRadius: 5,
        width: 300,
        height: 300,
    }
});

export default PictureList;

In the above component, we are building a picture list component which makes API call and parse the response to show a list of images on a mobile screen. We can use the same fetch function to make an API call. Fetch method is introduced in the web as part of ES6 specification. Fetch is used in the same way we used to use on a web browser. First, we created a class-based component and assigned list of images as the state of a component. Since we haven’t made an API call yet that is why the initial state of out PictureList component will be an empty array. In the render method, if our state is empty which means, we haven't received the response from a server that is why we are showing ActivityIndicator component provided by react-native. It is default spinner displayed on the screen. When our component is mounted then componentDidMount React lifecycle method get invoked, there we will make an API call and once we receive the response we update the state of PictureList component. Once the state is updated, the render method will get called and we render a list of images using FlatList and Image component.

We can divide all React Native components into two categories based on the internal state of the component. There are controls like textInput which have a value attribute. It is used to display user input value on UI. If the value displayed is controlled by the form control then it is known as an uncontrolled component because React is not setting or changing the value of these components. But if the state of the component is maintained by the state of the component then these components are called a controlled component. To make a component controlled, we assign the state of the component as the value of control elements and add a callback method which will update the state on each value change event. In React Native, it is preferred to have controlled component so that all the values and behaviour will get managed by React and developer will have full control over the state of components.

The basic definition of High order function is a function is called high order function if it either accept a function as an argument or returns another function. But now let’s talk about the benefit of writing a high order function. In javascript, we are trying to write less amount of code and try to reuse the same code or functionality at many times as we can. High order function way of writing code allows us to implement currying in Javascript. Now, what is this currying? Currying is a way of writing code where you write a common functionality and change the functionality via argument. Let me give you an example:

function multiplyBy(a) {
return function(b) {
return a * b;
};
}

This function is high order function as this returns a new function. This function will act as function generator for different functionalities. For example, I can create a double function by using the above high order function:

const double = multiplyBy(2);

console.log(double(4)) //result: 8

Similarly, I can use the same high order function to generate a triple function which takes the number as argument and return three times the number.

const triple = multiplyBy(3);

console.log(triple(4)) //result: 12

This type of function generation is known as currying in javascript. It is a better way of writing code as this decouples the base functionality with final logic. The base logic can be re-used at multiple places.

Just now, we have learned what high order functions are in Javascript and what are its benefits. With that knowledge, we can easily guess what a high order component will be and how it would be a good practise to use high order components wherever we can. Since components are also functions which are called as component in React world so High order components are components which take either component as an argument or returns another component. Higher order components are JavaScript functions used for adding additional functionalities to the existing component. These components are the pure component which means it doesn’t know any side effect. Its output is totally based on the input values. For example, connect function from a react-redux library is also a high order component. Connect takes mapStateToProps and mapDispatchToProps as an argument and returns a new component which can access redix store. The withProvider function of react-redux, the withRouter function of react-router are very well used function which is also an example of high order component.

Passing callback functions as a component prop is not new in Javascript world. We used to pass callback with events and also when we try to implement a controlled component. Slowly, react community has evolved a pattern based on passing a function as props. It is called the render prop pattern. The term “render props” refers to a technique for sharing code between React components using a prop whose value is a function. A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic. You can think of this pattern as a child component will call the prop function and the return element will be inserted by the parent component. It gives a way so that a child component can modify the structure of the parent component without dealing with Refs. React router is one library that has used this pattern. Below is a very good example of how to render prop patterns work:

const ProductDetail = ({ product }) => (
 <React.Fragment>
   <Text>{product.title}</Text>
   <Text>{product.description}</Text>
 </React.Fragment> )
<Fetch url=" some URL where my data is"
 render={(data) => <ProductDetail product={data.product} /> }
/>

You can clearly see that render prop will be called by Fetch child component and it will insert the product detail node in the parent component.

In ReactJS, as your application size is growing, you are going to have so many small or big component. At this stage, it’s always better to categorize and decided the roles and responsibilities of the component. Based on role and responsibilities, we can divide the component in two parts. One is a presentational component and another type of components are container component. We also call presentational component as a stateless component or dumb component. Container components are also known as a stateful component or smart component. It is very important to distinguish between the presentational component and the container component.

Presentational components show the following behaviour:

  1. These types of component are concerned with presentation and styling.
  2. These types of a component may contain both presentational and container components inside, and usually, have some DOM markup and styles of their own.
  3. These types of component Often allow containment via this.props.children.
  4. These types of component Don’t specify how the data is loaded or mutated. Data is passed to these type of component and they just create a markup to render the component.
  5. These types of component receive data and callbacks exclusively via props.
  6. These types of component rarely have their own state (when they do, it’s UI state rather than data).
  7. These types of components are written as functional component unless they need state, lifecycle hooks, or performance optimisations.

A mobile application contains multiple screens and there has to be a way to navigate through multiple screens in the application. Managing the presentation of, and transition between, multiple screens is typically handled by what is known as a navigator. React Navigation (https://reactnavigation.org/) provides an easy to use navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both iOS and Android. The community solution to navigation is a standalone library that allows developers to set up the screens of an app with just a few lines of code.

In Web development, if we don’t give a size to an element either via CSS or setting the width and height attribute of an element then elements size would be 0. There are a few instances where the size of the element is determined based on the size of children. For example, if you have an image element in div then initially height of div element is 0 and once the image is fetched from server browser again calculated the size of div and place image inside div. The user experience of this element is not very good as size keeps changing in between. If this div is placed in the middle of other div elements then the whole page will fluctuate to absorb the size of the image. To avoid this behaviour, React native have decided not to automatically calculate the size of elements. Instead, it completely depends on the developer to give the width and height of elements by CSS.

Debugging code is a very important aspect of development. The importance of debugging can be understood by the fact that debugging is also considered as a skill in software development. If a developer has a good debugging skill then there are chances and code will be of better quality and very well tested. To cater to this requirement of a developer, React native has provided pretty good support to debug the code. You can access the developer menu by shaking your device or by selecting "Shake Gesture" inside the Hardware menu in the iOS Simulator. You can also use the CMD + D keyboard shortcut when your app is running in the iOS Simulator, or CMD + M when running in an Android emulator on Mac OS and Ctrl+M on Windows and Linux. There are options to remotely debug the application via chrome browser. It will make the application a little slow but it is a good addition to enhance the development experience of the developer.

Virtual DOM was popularised by React core team member Pete Hunt. React explains its performance aspect by using this term. They explained that the DOM manipulation is always a heavy operation as browser reflow, repaint event gets triggered by DOM manipulation. The browser needs to recalculate the position of elements by upcoming change. To optimise this browser operation, ReactJS tries to minimize DOM manipulation operations. React creates an in-memory data structure cache, computes the resulting differences, and then updates the browser’s displayed DOM efficiently. This allows developers to write code as if the entire page is rendered on each change while the React libraries only render subcomponents that actually change. That is how React increases the space complexity by keeping data structure in memory but reducing the processing cost by reducing the number of DOM manipulation an updated needs to make an actual DOM.

In React, we follow component driven development, which means that we would be writing several stateful or stateless reusable components and combine them to build the entire application. Where your application is getting bigger then there are many instances where one component wants to access a state of any other component. One way to achieve this by putting a dependent component as children of the same parent and then can communicate via callbacks. These solutions work for small application but for a large application, passing callback from parent to innermost child element is cumbersome. That is where Redux comes in picture. Redux is a popular library to effectively maintain and manage the state of large React native application. It provides a store which keeps application level state and the developer needs to write actions and reducers to modify the state in the store. Any component can connect with the store by using Redux’s high order component connect. any component can dispatch an action which reaches to the reducer and updates the state in the store.

As javascript is evolving, people have started adding benefits of strictly typed languages like Java, C++. Typescript is one such framework which adds some very good features in javascript. But since those features are not supported by standard javascript yet, we would be needing tooling to convert the new concept in current concepts. That is done via using Babel in the build process. Languages that compile to JavaScript are generally compatible with React Native. React Native uses Babel to transform JavaScript into a form that is consumable by the native OS’s JavaScript runtime, using the react-native Babel plugin. As long as Babel can compile your JavaScript, and your code does not rely on the web- or Node.js-specific dependencies, it will run in React Native. So we can use compile-to-js libraries with React native but we need to add steps in the build process to convert typescript to React Native’s JS runtime consumable code.

React native provide Animated library out of the box which is designed to make animation fluid, maintainable and easy to build. It also provides a simple start/stop method to control time-based animations. Certain animation types, like Animation.timing and Animation.spring, can be serialized and sent across the asynchronous bridge before they are executed. This allows the runtime to defer the actual drawing of the animation entirely to the native side, instead of trying to send positional values across the bridge as each frame is rendered. This does not work with animations that are not computable ahead of time. We can combine multiple animations and can chain different animation steps to produce complex animations. By setting useNativeDriver: true in the animated config, we send all the animation information to the native, before starting the animation. This allows native code to perform the animation on UI thread without having to go through the bridge on every frame.

React Native comes with the Animated API built in. This API is declarative: We define specific animations, using Animated.timing, Animated.spring, etc., and provide the exact parameters needed for the animation to run. This technique falls apart when we need lots of subtle and delicate animations on the fly; it’s not performant, and maintaining all that code would be a nightmare. Instead, we look to the LayoutAnimation module, which is an interpolative API. We can invoke predefined LayoutAnimations, or define our own. LayoutAnimation watches changes in the positions of elements between cycles of the render loop and computes the positional differences between elements at different cycles. Then, it interpolates those changes and produces a smooth, natively driven animation.

If you have ever iterated through an array to create a list of component and in case you missed adding a key attribute with new elements, then React throws a warning that key is not assigned to elements. React uses Keys to identify unique Virtual Elements with their corresponding data driving the UI. They help React to optimise the rendering by recycling all the existing elements in the component. You can say that React uses these user given key values to identify the nodes. It makes a decision based on these keys whether the node should be updated or not. 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 by reducing the number of elements manipulations. In case you don’t find any unique value to assign to a node, the last resort will be to assign key of the node equals to index of the item.

Yes, TV devices support has been implemented with the intention of making existing React Native applications "just work" on Apple TV and Android TV, with few or no changes needed in the JavaScript code for the applications. Since there are lots of similarity between IOS and TvOS APIs, it was double to add TV support in React native. But there are not many developers using React native for building TV application. So at one point, the community were discussing to remove it from the core library also, people were facing few problems while using React native to develop TV apps. That is why React native documentation has a place where they have mentioned that React native can be used to make TV apps with less to no example about it. So technically, yes React native does support TV but community support and better documentation are not yet available.

Description

Want to become an expert in cracking React Native interview questions? Start with practising the questions below. Crack your next React Native interview with the frequently asked questions.
Levels