React Native Interview Questions and Answers

React Native is used to developing mobile applications for iOS, Android, and other platforms using JavaScript and React. It allows developers to use the same codebase for developing applications across multiple platforms, reducing the development time and cost. Whether you have a beginner, intermediate or expert level of proficiency, you can become a React Native developer with the proper skill set. Prepare for your interview with the best possible React Native interview questions and answers compiled by our experts that will help you crack your React Native interview and land a good job as a React Native Developer. Get ready to answer react native questions based on the benefits of using the UI software framework for building mobile applications, React Native tools, JSX, state and React Native components, Watchman, flexBox, constructing app pages, virtual DOM, animations, navigation and more. etc., and ace your next react native interview like a pro. Use this set of questions as a handy resource while giving a finishing touch to your interview prep.

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

Intermediate

React Native Overview: 

  • Developed by Facebook. 
  • Enables cross-platform mobile app development using JavaScript. 
  • Uses design principles from ReactJS. 

UI Development: 

  • Compose mobile application UI using multiple components declaratively. 

Comparison with Previous Options: 

  • Previous frameworks: Cordova, Ionic. 
  • Hybrid apps using these frameworks lacked native performance. 

Performance: 

  • React Native bridge invokes native rendering APIs (Objective-C for iOS, Java for Android). 
  • Provides better performance than hybrid frameworks. 

Community and Popularity: 

  • Active developer community. 
  • Code available on GitHub with over 70k stars. 
  • Quickly gained popularity in the React community. 

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.

Many renowned companies are developing their mobile apps with React Native. Big names like Facebook, Airbnb, Instagram, Pinterest, Uber, and Tesla have their main consumer-facing mobile apps built using this framework. This widespread adoption demonstrates their trust in React Native. 

Airbnb was an early adopter of React Native and actively shared their experiences with the framework. They also open-sourced many React Native libraries they built, one of the most famous being Lottie, which enables complex animations in React Native. 

Many startups are also using React Native to build their mobile apps, allowing them to quickly launch their ideas on both Android and iOS platforms simultaneously. Instagram, another example, uses React Native and handles large user interactions effectively. 

This clearly shows that React Native is a 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.

I’m listing down set of categories that shows how mobile app development is different than web app development using react —  

Origin and Architecture: Both developed and open-sourced by Facebook Inc., React Native follows ReactJS's basic architecture and promotes a component-based approach to building mobile screens. They share similar lifecycle methods.

UI Components: 

  • ReactJS: Uses HTML tags like div, span, etc. 
  • React Native: Uses components like View and Text from the React Native library. 

Platform and Browser Features: 

  • ReactJS: Built for web applications, allowing access to browser features like the window object and local storage. 
  • React Native: Built for native platforms, lacking access to browser-specific features. 

GitHub Projects: ReactJS and React Native are separate open-source projects on GitHub. 

Feature Implementation: New component architecture features are first implemented in ReactJS and later added to React Native. 

Development Tools: Both frameworks have different tools for getting started with development. 

Static Type Checking: 

  • React Native: Comes with static type checking enabled by default. 
  • ReactJS: Requires additional steps to enable flow static type checking. 

The above list of differentiation make clear how react and react native are works and different. 

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.

React 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.

React framework

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.

Introduction: Watchman is an open-source project developed by Facebook that monitors files and tracks changes. 

FunctionalityIt can trigger actions based on file changes. 

Hot Reloading in React Native: 

  • Watchman powers the hot reloading feature in React Native. 
  • Hot reloading allows developers to see changes immediately without recompiling the entire project. 
  • This feature speeds up development compared to traditional native mobile application development, which requires manual recompilation. 

Automation: When a developer makes changes in a React Native project file, Watchman detects the changes and triggers an automatic build, reflecting updates without manual intervention. 

Developer Benefits: The hot reloading feature makes React Native a developer-friendly framework, accelerating the development process. 

Setup: Installation of Watchman is included in the React Native environment setup instructions. 

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, the View component in React Native has its display property set to flex. Flex is a CSS property used to expand and shrink components dynamically based on available space. Setting flex: 1 on a component makes it take up all the available space. If a parent element has flex: 1, its child elements will evenly distribute the available space among themselves. 

The width of a child element can be adjusted by assigning it a higher flex value; the larger the value, the more space the component will take relative to its siblings. However, for a component to expand, its parent must have dimensions greater than zero. If the parent element's dimensions are not set, the flex property will not work, and the element will not be visible on the UI. 

In addition to the flex property, align-items and justify-content CSS properties are also used to design mobile UIs in React Native. 

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.

Transitions are an important feature of mobile devices. So, this is one of the most frequently asked React Native interview questions and answers for senior developer in recent times.

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

Functional component

Example of class-based component

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.

life cycle of a React component

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:

 basic text input to 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.

Basic button in 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.

Handling offline functionality involves: 

  • Data Storage: Use libraries like Redux Persist or AsyncStorage to store data locally. 
  • Synchronization: Sync local data with the server when the connection is restored. 
  • Fallback UI: Provide fallback UI elements to inform users about the offline status. 

These techniques ensure the app remains functional and provides a smooth user experience even without an internet connection. 

Code splitting improves performance by loading only the necessary code for the current screen. It can be achieved using: 

  • Dynamic Imports: Load components or modules only when needed. 
  • React.lazy and Suspense: Split code and load it asynchronously, reducing the initial bundle size. 

Code splitting helps optimize load times and enhances the app's performance by avoiding unnecessary code loading. 

Ensuring security involves several practices: 

  • Secure Storage: Use secure storage solutions for sensitive data. 
  • Input Validation: Validate and sanitize all user inputs to prevent injection attacks. 
  • Authentication and Authorization: Implement robust authentication mechanisms and restrict access to authorized users. 
  • Dependency Management: Keep dependencies updated to avoid known vulnerabilities. 

These practices help protect the application from common security threats and ensure data integrity. 

Managing app state can be done using: 

  • Redux Thunk: 
  • Allows writing action creators that return a function instead of an action. 
  • Suitable for simple asynchronous logic like API calls. 
  • Redux Saga: 
  • Uses generator functions to handle side effects more efficiently. 
  • Ideal for complex asynchronous workflows, allowing better control over execution flow. 

Both tools enhance state management in large applications by handling asynchronous actions effectively. 

Handling real-time updates involves: 

  • WebSockets: Establish a WebSocket connection for continuous data flow. 
  • Firebase: Use Firebase for real-time database synchronization and updates. 
  • Polling: Implement polling for periodic data fetching. 

These methods ensure the app stays updated with the latest data, providing a dynamic user experience. 

Keys in React Native are crucial for: 

  • Identification: Help React identify which items have changed, are added, or are removed. 
  • Performance: Improve performance by enabling efficient re-rendering of lists. 
  • Order Management: Ensure elements are correctly ordered and maintained during updates. 

Keys should be unique to ensure React can manage component updates accurately. 

Managing app state can be done using: 

  • Redux Thunk: 
    • Allows writing action creators that return a function instead of an action. 
    • Suitable for simple asynchronous logic like API calls. 
  • Redux Saga: 
    • Uses generator functions to handle side effects more efficiently. 
    • Ideal for complex asynchronous workflows, allowing better control over execution flow. 

Both tools enhance state management in large applications by handling asynchronous actions effectively. 

Yes, React Native can be used for building TV applications: 

  • React Native for TV: Extends the core framework to support TV devices like Apple TV and Android TV. 
  • TV-specific Components: Provides components and navigation patterns tailored for TV interfaces. 

While React Native supports TV app development, community support and documentation are still evolving. 

Native Modules allow integrating custom native code into a React Native app: 

  • Custom Code: Write native code in Java (Android) or Objective-C/Swift (iOS). 
  • JavaScript Bridge: Expose native functionalities to JavaScript through the bridge. 
  • Integration: Use NativeModules to access and utilize native modules in the React Native app. 

Native Modules provide flexibility to leverage platform-specific features and optimize performance. 

Integrating third-party libraries involves: 

  • Installation: Use npm or yarn to install the library. 
  • Linking: Use react-native link or manually link the library if needed. 
  • Configuration: Follow the library's setup instructions for configuration and usage. 

These steps ensure the library is correctly integrated and functional within the React Native app. 

The 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 the component, unlike props. We should not directly change the state value of the react component. React framework gives the setState method by which the 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; 
 

The 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 (-) buttons. 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 and 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 components in React to build the complete application. 

React Native follows the box model concept of CSS, where the size of an element is determined by its content, padding, border, and margin. The simplest way to set an element's size is by specifying the width and height CSS properties. In React Native, all dimensions are unitless and represent density-independent pixels, ensuring consistent element sizes across different screen sizes when using fixed values. 

However, if you need to set dimensions as a percentage, React Native does not directly support this. Instead, it provides the Dimensions module, which gives the width and height of the mobile device. This information can be used to dynamically set an element's style at runtime, allowing for responsive design by calculating percentage-based dimensions. 

Below is an example of how to use the Dimension module from React native: 

Importing module from React Native: 

import { Dimension } from ‘react-native’; 

Figure out the 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. 

CSS Flexbox is used to design responsive layouts easily, without relying on float or position CSS properties, which can be cumbersome. Introduced in CSS3, Flexbox ensures consistent layouts across different screen sizes. 

In React Native, you typically use a combination of flexDirection, alignItems, and justifyContent to achieve the desired layout. There are some differences in the default values of certain flex-based CSS properties between React Native and web browsers: 

  • flexDirection: Defaults to row on the web, but to column in React Native. 
  • flex: In React Native, the flex parameter supports only a single number. 

Flexbox properties like alignItems and justifyContent help position elements: 

  • alignItems: Values like flex-start align elements from the start, while flex-end places the first child element at the end. 
  • justifyContent: Similar to alignItems, it positions elements along the main axis. 

These properties allow for easy and flexible layout designs, ensuring responsive and adaptive UIs across different devices. 

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 vertical in the case of React native. This 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 applies some control over the alignment of items when they overflow the line. Let me explain JustifyContent’s values: 

  1. flex-start: this is the default value for justifyContent. It means that flex items will start from the top and be evenly distributed vertically. 
  2. Flex-end: this is just the opposite behavior of flex-start. Elements start rendering from the bottom 
  3. Center: Items will be placed in the middle 
  4. Space-between: elements are evenly distributed along the main axis (vertical axis) 
  5. 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 the 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 horizontal in the 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 align items values: 

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

By default, the main axis is the vertical axis, and the cross axis is the horizontal axis in React native. Since justifyContent and alignItems properties work based on the main axis and cross axis, so justifyContent will align flex items vertically and alignItems will layout flex items horizontally.  

This default value of the main axis and cross axis can be changed by changing the flexDirection property. If we set flexDirection to row in the flex container then the main axis will become the horizontal axis and the cross axis will become the vertical axis.  

On changing the default behavior via the flexDirection CSS property, the behavior of alignItems and justifyContent will also get switched. The Concept of flex-direction is also present on the web. Flexbox is implemented as a single-direction layout technique and this direction is managed by the 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.  

Transitions are an important feature of mobile devices. So, this is one of the most frequently asked React Native interview questions and answers for senior developers in recent times. 

Handling performance issues involves several strategies: 

  • Optimize Images: Use appropriate formats and sizes, and consider using image caching. 
  • Use FlatList and SectionList: For handling large lists efficiently. 
  • Reduce Re-renders: Use React.memo, PureComponent, and avoid inline functions in render methods. 
  • Optimize State Management: Use state management libraries like Redux or Context API to minimize unnecessary state updates. 
  • Profiling: Use performance profiling tools to identify and address bottlenecks. 

Handling authentication typically involves: 

  • OAuth: Use libraries like react-native-app-auth for OAuth-based authentication. 
  • JWT: Store JSON Web Tokens securely using AsyncStorage or SecureStore for secure sessions. 
  • Backend Integration: Implement authentication logic on the backend and manage session states through APIs. 

Common debugging techniques include: 

  • React Native Debugger: A standalone app for debugging React Native apps. 
  • Console Logging: Use console.log statements for quick debugging. 
  • Remote Debugging: Use Chrome DevTools for inspecting network requests, debugging code, and profiling performance. 
  • Error Boundaries: Implement error boundaries to catch and handle errors gracefully. 

Managing dependencies involves: 

  • Package Managers: Use npm or yarn to manage dependencies. 
  • Versioning: Keep track of dependency versions in package.json. 
  • Regular Updates: Regularly update dependencies to benefit from the latest features and security patches. 
  • Peer Dependencies: Ensure peer dependencies are compatible to avoid version conflicts. 

Handling internationalization involves: 

  • Libraries: Use libraries like react-i18next or react-native-localize. 
  • Translation Files: Store translations in JSON files or similar formats. 
  • Locale Detection: Detect the user's locale using react-native-localize and load the corresponding translation files. 
  • Dynamic Content: Ensure dynamic content like dates and currencies are formatted according to the locale. 

Testing a React Native app involves: 

  • Unit Testing: Use Jest for unit testing components and logic. 
  • Integration Testing: Use testing libraries like Enzyme or React Native Testing Library for integration tests. 
  • End-to-End Testing: Use tools like Detox for end-to-end testing to simulate real user interactions. 

Best practices include: 

  • Modular Architecture: Organize code into modules based on features or functionality. 
  • Folder Structure: Use a consistent folder structure, such as separating components, screens, and services. 
  • Reusable Components: Create reusable components to avoid code duplication. 
  • Clear Naming Conventions: Use clear and descriptive names for files and variables. 

Handling background tasks involves: 

  • Background Fetch: Use the react-native-background-fetch library for periodic background tasks. 
  • Background Timer: Use react-native-background-timer for scheduling tasks. 
  • Push Notifications: Use push notifications to trigger background tasks. 
  • Platform APIs: Utilize platform-specific APIs for handling background tasks efficiently. 

Handling file uploads involves: 

  • FormData: Use FormData to create a form and append files. 
  • Fetch API: Use the Fetch API to send the FormData to the server. 
  • React Native Image Picker: Use the react-native-image-picker library to select files from the device. 
  • Progress Tracking: Use libraries like react-native-fetch-blob to track upload progress. 

Beginner

To handle global state in a React Native app, I use state management libraries like Redux or the Context API: 

  • Redux: Provides a centralized store for the entire application state, making it easy to manage and debug state changes. Redux uses actions, reducers, and a store to manage state. 

  • Context API: Allows passing data through the component tree without manually passing props at every level. It's useful for smaller applications or when you don't need the full power of Redux. 

Both methods help maintain a consistent state across the app, reducing the complexity of prop drilling. 

The useEffect hook in React Native allows us to perform side effects in functional components. It can be used for: 

  • Data fetching: Load data when the component mounts. 
  • Subscriptions: Set up and clean up subscriptions like WebSockets. 
  • Manual DOM manipulation: Perform updates that need to directly interact with the DOM or native elements. 

useEffect runs after the initial render and can re-run based on dependencies, making it versatile for managing side effects. 

To handle navigation between screens in React Native, I use the React Navigation library. It provides: 

  • Stack Navigator: Manages a stack of screens with a header and back button. 
  • Tab Navigator: Creates a tabbed interface for switching between screens. 
  • Drawer Navigator: Adds a sidebar for navigation. 

React Navigation is highly customizable and supports deep linking, providing a seamless navigation experience across different platforms. 

Optimizing performance in a React Native app involves several strategies: 

  • Memoization: Use React.memo and PureComponent to prevent unnecessary re-renders. 
  • Optimized Lists: Use FlatList and SectionList for handling large data sets efficiently. 
  • Image Optimization: Compress and cache images to reduce load times. 
  • Production Mode: Enable production mode to leverage optimizations like minification and dead code elimination. 

These techniques help improve the app's responsiveness and reduce resource consumption. 

The differences between componentDidMount and useEffect are: 

  • componentDidMount: 
    • Used in class components. 
    • Called once after the initial render. 
    • Ideal for initial data fetching and setup. 
  • useEffect: 
    • Used in functional components. 
    • Can run after every render or conditionally based on dependencies. 
    • More versatile for managing side effects and cleanup. 

Using useEffect provides greater flexibility and aligns with the functional programming approach. 

Handling API errors in React Native involves: 

  • Try-catch blocks: Wrap async functions in try-catch blocks to handle errors gracefully. 
  • Response status checks: Check response status and handle different HTTP status codes appropriately. 
  • User Feedback: Display error messages or notifications to inform users about issues. 

These practices ensure robust error handling and improve the user experience by providing meaningful feedback. 

Hooks are functions that let us use state and other React features in functional components. They provide several benefits: 

  • Simplified Code: Reduce the need for class components, making code easier to read and maintain. 
  • State Management: Use useState for managing component state and useReducer for complex state logic. 
  • Side Effects: Use useEffect for handling side effects like data fetching and subscriptions. 

Hooks make it easier to share logic between components and align with modern React development practices. 

Handling forms in React Native involves: 

  • Controlled Components: Use state to manage form inputs, ensuring form data is synchronized with component state. 
  • Libraries: Utilize libraries like Formik for managing form state and validation. 
  • Validation: Implement validation using libraries like Yup to ensure form data integrity. 

These practices ensure efficient form handling, data validation, and improved user interactions. 

To implement dark mode in a React Native app, I use the useColorScheme hook: 

  • Detect System Theme: Use useColorScheme to determine if the device is in light or dark mode. 
  • Conditional Styles: Apply different styles based on the current theme. 
  • Theme Context: Create a ThemeContext to manage and provide theme-related data across the app. 

This approach allows the app to adapt to the system's theme, providing a seamless user experience. 

Using TypeScript with React Native offers several benefits: 

  • Type Safety: Reduces runtime errors by catching type-related issues during development. 
  • Better Tooling: Enhanced IDE support with features like auto-completion and type checking. 
  • Code Readability: Improves code readability and maintainability by providing explicit type definitions. 

TypeScript helps create more robust and reliable applications by adding a layer of type safety to JavaScript. 

The differences are: 

  • Synchronous: 
    • Code executes line-by-line, waiting for each operation to complete before moving to the next. 
    • Blocks subsequent code execution until the current operation finishes. 
  • Asynchronous: 
    • Allows other operations to run while waiting for a task to complete. 
    • Utilizes callbacks, promises, or async/await to handle non-blocking operations. 

Asynchronous functions improve efficiency by allowing concurrent execution of tasks. 

Let’s see what is component driven development and how it benefits –  

  1. Early Realizations: Web developers recognized the frequent use of elements like drop-downs and buttons, leading to the creation of CSS frameworks. 
  2. Bootstrap's Impact: Bootstrap was the first popular CSS framework, helping developers build user experiences quickly. 
  3. React's Approach: React follows a similar approach with component-driven development, breaking UI design into small, reusable components. 
  4. Modular Code: This methodology promotes writing UI code in a modular way, enhancing code reusability and speeding up development. 
  5. Maintenance and Bugs: Less code means less effort in maintenance and fewer bugs. 
  6. Popularity: While component-driven development existed before, React JS popularized it in the developer community. 
  7. Adoption by Other Frameworks: New frameworks like Angular (version 4 and above) also adopt this methodology for web application development. 

Handling navigation state involves: 

  • React Navigation: Use React Navigation's state management features to keep track of navigation state. 
  • Redux Integration: Integrate navigation state with Redux for a centralized state management solution. 
  • Persistence: Persist navigation state across app launches using libraries like AsyncStorage. 

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

logic screen in React Native

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.

This, along with other React Native basic interview questions for freshers, is a regular feature in React Native interviews, be ready to tackle it with the approach mentioned.

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.

Expect to come across this, one of the most important React Native interview questions for experienced professionals in mobile app development, in your next interviews.

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.

React Native application

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.

A must-know for anyone looking for top React Native interview questions and answers, this is one of the frequently asked React Native interview questions based on actual use cases.

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.

This is an advanced React Native interview question based on screen navigation in mobile applications. Don't be surprised if this question pops up as one of the top interview questions for React Native in your next interview.

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 crucial aspect of development, regarded as a skill in software development. A developer with strong debugging skills can produce higher quality, well-tested code. To support this need, React Native offers robust debugging tools. 

Accessing the Developer Menu: 

  • Shake Gesture: Shake your device or select "Shake Gesture" from the Hardware menu in the iOS Simulator. 
  • Keyboard Shortcuts: 
  • iOS Simulator: Press CMD + D. 
  • Android Emulator on Mac OS: Press CMD + M. 
  • Android Emulator on Windows and Linux: Press Ctrl + M. 

Remote Debugging: 

  • You can remotely debug the application via the Chrome browser. Although this may slow down the application slightly, it significantly enhances the development experience. 

So, React Native provides extensive support for debugging, making it easier for developers to identify and fix issues, thereby improving code quality and testing. 

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.

A staple in React Native technical interview questions, be prepared to answer this one using your hands-on experience with animations.

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 device support has been implemented with the intention of making existing React Native applications work seamlessly on Apple TV and Android TV with minimal or no changes needed in the JavaScript code. Due to the similarities between iOS and tvOS APIs, adding TV support to React Native was feasible. However, there are not many developers using React Native for building TV applications. 

At one point, the community considered removing TV support from the core library due to issues developers faced while using React Native for TV apps. Consequently, the React Native documentation mentions that React Native can be used to develop TV apps but provides few examples. So, technically, React Native does support TV, but community support and comprehensive documentation are still lacking. 

Deep linking in React Native is managed using React Navigation and Linking API: 

  • React Navigation: Configure the navigator with deep linking support. 
  • Linking API: Use the Linking module to handle incoming URLs and navigate to the appropriate screen. 
  • Custom Schemes: Define custom URL schemes for the app to handle specific links. 

Deep linking enhances user experience by allowing direct navigation to specific content within the app from external sources. 

Best practices for managing performance in a React Native app include: 

  • Optimizing ImagesUse appropriate image formats and sizes. 
  • Minimizing State Updates: Avoid unnecessary state updates and re-renders. 
  • Using PureComponent and memo: Prevent re-renders for components that don't need to update. 
  • Virtualized ListsUse FlatList and SectionList for large datasets. 
  • Monitoring and Profiling: Utilize tools like React Native Debugger and performance monitors. 

Following these practices helps maintain a smooth and responsive user experience. 

To implement push notifications: 

  • Firebase: Use Firebase Cloud Messaging (FCM) for push notifications. 
  • React Native Firebase: Integrate the react-native-firebase library. 
  • Configuration: Set up Firebase in the app, including API keys and configuration files. 
  • Notification Handling: Handle notifications in the background and foreground using the library's methods. 

Push notifications keep users engaged and informed about important updates. 

The difference between controlled and uncontrolled components: 

  • Controlled Components: The component's value is managed by React state. Changes to the value are handled through state updates. 
  • Uncontrolled Components: The component maintains its own internal state. Values are accessed using refs. 

Controlled components provide better control and synchronization with the app's state, while uncontrolled components can be simpler for basic use cases. 

Handling complex animations involves: 

  • Animated API: Use the Animated library for creating complex animations. 
  • Reanimated: Use the react-native-reanimated library for more advanced animations. 
  • Combining Animations: Chain multiple animations together using sequence and parallel functions. 
  • Native Driver: Use the native driver for smoother performance. 

These tools and techniques allow for creating engaging and performant animations. 

Ensuring accessibility involves: 

  • Accessibility Properties: Use properties like accessible, accessibilityLabel, and accessibilityHint. 
  • VoiceOver and TalkBack: Test the app with screen readers on both iOS and Android. 
  • Semantic Elements: Use semantic components and ARIA roles to improve navigation and interaction for users with disabilities. 

Accessibility improves the app's usability for all users, including those with disabilities. 

Managing environment variables involves: 

  • react-native-config: Use the react-native-config library to manage environment variables. 
  • Environment Files: Define variables in .env files for different environments (e.g., .env.dev, .env.prod). 
  • Accessing Variables: Access variables in the app using Config from the react-native-config library. 

This approach allows for secure and easy management of environment-specific configurations. 

To handle deep linking: 

  • Linking API: Use the Linking module to listen for incoming links and navigate to the corresponding screen. 
  • Navigation Configuration: Configure React Navigation to support deep links. 
  • Custom Schemes: Define custom URL schemes for handling specific types of links. 

Deep linking improves user experience by allowing direct navigation to specific content within the app. 

Implementing error boundaries involves: 

  • Error Boundary Component: Create a component that catches JavaScript errors anywhere in the component tree. 
  • ComponentDidCatch: Use the componentDidCatch lifecycle method to log errors and display a fallback UI. 
  • Usage: Wrap critical parts of the app with the error boundary component. 

Error boundaries prevent the app from crashing and provide a better user experience during unexpected errors. 

Advantages of using React Native: 

  • Cross-Platform Development: Write once and deploy on both iOS and Android. 
  • Faster Development: Reuse code across platforms, reducing development time. 
  • Hot Reloading: Instantly see code changes without recompiling. 
  • Large Community and Ecosystem: Access to a vast number of libraries and community support. 
  • Cost-Effective: Lower development and maintenance costs due to shared codebase. 

These advantages make React Native a popular choice for building mobile applications.