Accreditation Bodies
Accreditation Bodies
Accreditation Bodies
Supercharge your career with our Multi-Cloud Engineer Bootcamp
KNOW MOREReact 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.
Filter By
Clear all
React Native Overview:
UI Development:
Compose mobile application UI using multiple components declaratively.
Comparison with Previous Options:
Performance:
Community and Popularity:
There are following benefits of using React Native in mobile application development
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:
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:
Platform and Browser 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:
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.
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.
Introduction: Watchman is an open-source project developed by Facebook that monitors files and tracks changes.
Functionality: It can trigger actions based on file changes.
Hot Reloading in React Native:
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:
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:
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:
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
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:
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.
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.
Handling offline functionality involves:
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:
Code splitting helps optimize load times and enhances the app's performance by avoiding unnecessary code loading.
Ensuring security involves several practices:
These practices help protect the application from common security threats and ensure data integrity.
Managing app state can be done using:
Both tools enhance state management in large applications by handling asynchronous actions effectively.
Handling real-time updates involves:
These methods ensure the app stays updated with the latest data, providing a dynamic user experience.
Keys in React Native are crucial for:
Keys should be unique to ensure React can manage component updates accurately.
Managing app state can be done using:
Both tools enhance state management in large applications by handling asynchronous actions effectively.
Yes, React Native can be used for building TV applications:
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:
Native Modules provide flexibility to leverage platform-specific features and optimize performance.
Integrating third-party libraries involves:
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:
Flexbox properties like alignItems and justifyContent help position elements:
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:
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:
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:
Handling authentication typically involves:
Common debugging techniques include:
Managing dependencies involves:
Handling internationalization involves:
Testing a React Native app involves:
Best practices include:
Handling background tasks involves:
Handling file uploads involves:
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:
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:
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:
These techniques help improve the app's responsiveness and reduce resource consumption.
The differences between componentDidMount and useEffect are:
Using useEffect provides greater flexibility and aligns with the functional programming approach.
Handling API errors in React Native involves:
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:
Hooks make it easier to share logic between components and align with modern React development practices.
Handling forms in React Native involves:
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:
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:
TypeScript helps create more robust and reliable applications by adding a layer of type safety to JavaScript.
The differences are:
Asynchronous functions improve efficiency by allowing concurrent execution of tasks.
Let’s see what is component driven development and how it benefits –
Handling navigation state involves:
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.
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.
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:
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:
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:
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:
Following these practices helps maintain a smooth and responsive user experience.
To implement push notifications:
Push notifications keep users engaged and informed about important updates.
The difference between controlled and uncontrolled components:
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:
These tools and techniques allow for creating engaging and performant animations.
Ensuring accessibility involves:
Accessibility improves the app's usability for all users, including those with disabilities.
Managing environment variables involves:
This approach allows for secure and easy management of environment-specific configurations.
To handle deep linking:
Deep linking improves user experience by allowing direct navigation to specific content within the app.
Implementing error boundaries involves:
Error boundaries prevent the app from crashing and provide a better user experience during unexpected errors.
Advantages of using React Native:
These advantages make React Native a popular choice for building mobile applications.
React Native Overview:
UI Development:
Compose mobile application UI using multiple components declaratively.
Comparison with Previous Options:
Performance:
Community and Popularity:
There are following benefits of using React Native in mobile application development
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:
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:
Platform and Browser 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:
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.
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.
Introduction: Watchman is an open-source project developed by Facebook that monitors files and tracks changes.
Functionality: It can trigger actions based on file changes.
Hot Reloading in React Native:
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:
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:
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:
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
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:
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.
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.
Handling offline functionality involves:
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:
Code splitting helps optimize load times and enhances the app's performance by avoiding unnecessary code loading.
Ensuring security involves several practices:
These practices help protect the application from common security threats and ensure data integrity.
Managing app state can be done using:
Both tools enhance state management in large applications by handling asynchronous actions effectively.
Handling real-time updates involves:
These methods ensure the app stays updated with the latest data, providing a dynamic user experience.
Keys in React Native are crucial for:
Keys should be unique to ensure React can manage component updates accurately.
Managing app state can be done using:
Both tools enhance state management in large applications by handling asynchronous actions effectively.
Yes, React Native can be used for building TV applications:
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:
Native Modules provide flexibility to leverage platform-specific features and optimize performance.
Integrating third-party libraries involves:
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:
Flexbox properties like alignItems and justifyContent help position elements:
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:
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:
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:
Handling authentication typically involves:
Common debugging techniques include:
Managing dependencies involves:
Handling internationalization involves:
Testing a React Native app involves:
Best practices include:
Handling background tasks involves:
Handling file uploads involves:
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:
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:
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:
These techniques help improve the app's responsiveness and reduce resource consumption.
The differences between componentDidMount and useEffect are:
Using useEffect provides greater flexibility and aligns with the functional programming approach.
Handling API errors in React Native involves:
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:
Hooks make it easier to share logic between components and align with modern React development practices.
Handling forms in React Native involves:
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:
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:
TypeScript helps create more robust and reliable applications by adding a layer of type safety to JavaScript.
The differences are:
Asynchronous functions improve efficiency by allowing concurrent execution of tasks.
Let’s see what is component driven development and how it benefits –
Handling navigation state involves:
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.
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.
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:
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:
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:
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:
Following these practices helps maintain a smooth and responsive user experience.
To implement push notifications:
Push notifications keep users engaged and informed about important updates.
The difference between controlled and uncontrolled components:
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:
These tools and techniques allow for creating engaging and performant animations.
Ensuring accessibility involves:
Accessibility improves the app's usability for all users, including those with disabilities.
Managing environment variables involves:
This approach allows for secure and easy management of environment-specific configurations.
To handle deep linking:
Deep linking improves user experience by allowing direct navigation to specific content within the app.
Implementing error boundaries involves:
Error boundaries prevent the app from crashing and provide a better user experience during unexpected errors.
Advantages of using React Native:
These advantages make React Native a popular choice for building mobile applications.
React Native is a JavaScript framework used by software developers to build cross-platform mobile apps using JavaScript. It was released by Facebook in 2015. React Native within a short period of time got massive popularity among the developers. Today, the mobile app development industry has witnessed miraculous growth among many sectors. According to Statista, mobile apps are predicted to generate $613 billion in global revenue through in-app advertising and app stores by the year 2025.
React Native has accomplished community support, massive popularity, and market share within the few years since it was introduced. React Native is used by many Fortune 500 companies like Facebook, Walmart, Skype, Instagram, Tesla, Bloomberg, etc. to name a few.
If you are planning to start your career in React then you need to be well prepared with all the possible React Native interview questions which could be asked in the upcoming Native developer interview. Courses in web development are very likely to introduce you to these react native questions and allows you to have a practical answer to a lot of scenario-based react native questions. There are several complicated React Native developer interview questions you might come across in the interview.
With a lot of research, we have brought you the top interview questions on React Native that you might encounter in your upcoming interview. These basic React Native interview questions for experienced and freshers alone will help you crack the interview questions on React Native and give you an edge over your competitors. So, in order to succeed in the interview, you need to prepare with these React technical interview questions on a regular basis.
Stay focused on the essential React Native technical interview questions and prepare well to get acquainted with the types of questions that you may come across in your interview.
Hope these advanced React Native interview questions will help you to crack the interview. If you like learning with mentors, enroll in a React Native course led by virtual instructors on your own schedule. All the best!
Submitted questions and answers are subjecct to review and editing,and may or may not be selected for posting, at the sole discretion of Knowledgehut.
Get a 1:1 Mentorship call with our Career Advisor
By tapping submit, you agree to KnowledgeHut Privacy Policy and Terms & Conditions