React Native top 80 interview questions
What is a render prop?
A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.
What is the use of an arrow function in react?
An error function is used to write an expression and react.
Differentiate between angular and react
Angular utilizes real DOM where is react utilizes virtual DOM. Angular's architecture is full MVC support where reacts is only the view aspect of MVC.
How can you use Axios in React Native?
Axios is a famous library if you want to make HTTP requests from the browser. We can make the POST, GET, DELETE, AND PUT requests from the browser. That's why React Native uses the Axios for making requests to an API, returning data from API, and performing actions with the data in React Native application. By using the given command, we can use Axios via the addition of the Axios plugin to the project.
List the ways to write react components.
Class-based component: It uses the class keyword, which is introduced in ES6. The render lifecycle method that returns the JSX is used here. Functional component: A simple function is used here that returns the JSX
What are components in react?
Components or foundations used to build user interface is for applications are completely reusable and independent
How do you call a Web API in React Native?
Fetch
Mention some ways of handling different screen sizes.
Flexbox Dimensions Pixel ratio ScrollView AspectRatio
Describe Flexbox along with its most used properties.
Flexbox is a layout mode that enables elements to coordinate and distribute space within containers. It provides a consistent layout on different screen sizes. The main properties in Flexbox are flexDirection, justifyContent, and alignItems. Let's discuss what each of these properties does: flexDirection: used to specify the alignment of elements (vertical or horizontal) justifyContent: used to decide how elements should be distributed inside a given container alignItems: used to specify the distribution of elements inside a given container along the secondary axis
What is the function of Flexbox in React Native?
Flexbox is a layout model. The function of Flexbox is aligning and distributing the space within a container. It is a great tool that is used for responsive design systems. Its most used properties are flexDirection, justifyContent, and alignItems.
What are the top alternatives to React Native, in your opinion?
Flutter Xamarin Nativescript
What is the difference between a functional component and a class component?
Functional components are also known as stateless components. Functional components accept props and return HTML. They give solutions without using state, and they can be defined with or without arrow functions. Class components are also known as stateful components. They're ES6 classes that extend the component class from the React library. They implement logic and state. Class components need to have render() method when returning HTML. You can pass props to them and access them with this.props.
What is the Gesture Responder System in React Native?
Gesture Responder System is React Native's internal system, which manages the lifecycle of the system of gestures. Sliding, tapping, zooming, and swiping are some of the various kinds of gestures that React Native provides. These touch interactions are negotiated by the responder system. We use the Animated API generally. And we can't reverse the gestures once made.
What are higher order components in react?
HOC's are a widely used technique and react for applying concepts that involve the component reusability logic
What are Higher Order Components (HOC) and how do you use them?
Higher-order components are pure functions that take components and return new components. Their main purpose is to condense and reuse stateful logic across different components. They're considered to be advanced techniques, and they aren't a part of the React API. Instead, they're patterns that emerge from React's compositional nature.
What are hooks in react?
Hooks are used to make use of the state and other features without having to write a class.
What is state and how do you use it?
In React Native, state handles data that is changeable. state is mutable, meaning that it can change the value at any time. You should initialize it in the constructor, and then call setState when you want to change it.
Describe how the Virtual DOM works.
In React Native, the Virtual DOM is a copy of the real DOM. It's a node tree that lists elements along with their attributions, contents, and properties. Whenever our underlying data changes, the Virtual DOM will re-render the UI. After that, the differences between other DOM representations and Virtual DOM representations will be counted, and the real DOM will update.
What is the difference between virtual DOM and real DOM?
In virtual DOM changes can be made easily there a faster updates and there is minimal memory wastage. In real Dom changes can be expensive updates are slow and there is high demand for memory and more memory wastage.
What is JSX?
It is a syntax extension to JavaScript. JSX produces React "elements". JavaScript XML, or JSX, is a XML/HTML template syntax used by React. It extends ECMAScript, which allows XML/HTML-like text to coincide with JavaScript and React code. It allows us to put HTML into JavaScript. It's faster than normal JavaScript, makes it easier to create templates, and uses components. It comes with the full power of JavaScript, and you can use it with React to describe what the user interface should look like. Let's take a look at a Hello World! in JSX: const element = <h1>Hello World!</h1>
Explain setNativeProps. Does it create Performance issues and how is it used ?
It is sometimes necessary to make changes directly to a component without using state/props to trigger a re-render of the entire subtree. When using React in the browser, for example, you sometimes need to directly modify a DOM node, and the same is true for views in mobile apps. setNativeProps is the React Native equivalent to setting properties directly on a DOM node. Use setNativeProps when frequent re-rendering creates a performance bottleneck. Direct manipulation will not be a tool that you reach for frequently; you will typically only be using it for creating continuous animations to avoid the overhead of rendering the component hierarchy and reconciling many views. setNativeProps is imperative and stores state in the native layer (DOM, UIView, etc.) and not within your React components, which makes your code more difficult to reason about. Before you use it, try to solve your problem with setState and shouldComponentUpdate
What is JSX?
JSX is JavaScript XML used in react to bring out JavaScript in HTML ensures high readability and increases the performance of the application
Are there any disadvantages to using react
Library has a huge repository of information which might be overwhelming.
What are important features of react?
Makes use of a single direction data flow model and uses virtual DOM
What are some causes of memory leaks and how can you detect them for IOS and Android?
Memory leaks can happen if unreleased timers or listeners are added in componentDidMount or with closure scope leaks. To detect memory leaks for IOS, you go to Xcode, Product, then Profile. To detect memory leaks for Android, you can use the Performance Monitor.
Imagine you have an app which is a series of lists of images (e.g. like Instagram). The app seems to crash at random. What steps can we take to investigate and mitigate this in React Native?
Often, and especially on the Android platform, lists of images are not properly recycled when scrolling. Their memory is never garbage collected, nor is it manually freed at a lower level. This leads to out-of-memory (OOM) crashes that can occur seemingly at random as the app's memory is exhausted. We can investigate this by profiling the app's heap memory usage in either Xcode or Android Studio. If you scroll through a list of images and notice the heap usage steadily climbing without ever dipping, it probably means that your images aren't being recycled properly. To mitigate this, we can check which list implementation we are using. In modern versions of React Native, ListView should never be used; ensure that the FlatList component is handling the rendering instead. If this is not sufficient after tuning, you can try making your images lower resolution.
How can you fetch data from a local JSON file in React Native?
Options: 1: const customData = require("./customData.json"); 2: import * as data from "./example.json"; const word = data.name; console.log(world);
What are props in react?
Props are read only components that are immutable follow a hierarchy that is passed down from parent to child components has single directional flow in data at all times.
What is meant by Props drilling?
Props drilling or threading is the process of passing down the data from the parent component to its exact child component. In between, it passes through other components which own the props.
What is the difference between props and states?
Props have changes in child components but don't have changes inside components, but states have changes inside components.
Native apps that feel smooth often incorporate lots of little animations for state changes and transitions. How would you implement these behaviors?
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.
How is React Native different from ReactJS?
React Native is a JavaScript framework that was developed by Facebook to meet the growing needs of mobile app development. It's open-source and based on JavaScript. It was designed to build native mobile apps with reusable components. It uses a lot of ReactJS components but implements them in a native way across different devices. It invokes the native rendering APIs in Objective-C (for IOS) and Java (for Android). ReactJS was also developed by Facebook. It's an open-source JavaScript library used for developing responsive user interfaces for mobile and web applications. It has a library of reusable components that are meant to help developers build the foundation for their apps. Let's take a look at some of their key differences: Syntax: React Native and ReactJS both use JSX, but ReactJS uses HTML tags, and React Native doesn't. Navigation: React Native uses its own built-in navigation library, while ReactJS uses a react-router. Animation: ReactJS uses CSS animations. React Native uses its animated API. DOM: ReactJS uses a virtual DOM with a partial refresh. React Native needs to use its native API when rendering UI components. Usage: ReactJS is mainly used for web app development, while React Native focuses on mobile applications.
What is react?
React is a JavaScript library primarily used for front end development to design user interfaces and web applications
What is Reconciliation in React.js?
React provides a declarative API so that you don't have to worry about exactly what changes on every update. This makes writing applications a lot easier, but it might not be obvious how this is implemented within React. This article explains the choices we made in React's "diffing" algorithm so that component updates are predictable while being fast enough for high-performance apps.
What is Redux and when should you use it?
Redux is a state management tool for JavaScript applications. It helps you write apps that are consistent, apps that can be run in different environments, and apps that are easy to test. Not all applications need Redux. It's designed to help you determine when you experience state changes. According to the official Redux documentation, here are some examples of when you'd want to use Redux: Your app state is updated frequently You have a large amount of app state and it's needed in many places within the app The logic to update your app state is complicated You want to see how the state is being updated over time Your app has a medium or large-sized codebase and will be worked on by multiple people
What is the meaning of redux
Redux is used to store the state of the application in a single entity usually is a JavaScript object
What is meant by Refs in React Native?
Refs in React Native are the features used for accessing a component's instance or DOM elements directly within React. In situations where you wish to change a child's component without the component's re-rendering or the use of props, Refs come to your rescue.
How can you improve the performance (load speed, rendering quality) of images?
Server-side compression Third-party tools such as Cloudinary Image caching
What are the threads used in React Native?
Shadow Thread: it's a background thread. We can calculate a layout created using React library inside React Native by this thread. MAIN/UI Thread: It's the main thread on which our app runs. JavaScript Thread: it executes the main Javascript code.
Mention the similarities between React Native and React.
Some of the similarities between React Native and React are given below: React components React lifecycle methods Redux libraries React states and props
Why do we use StyleSheet.create? What are the tradeoffs with this approach?
StyleSheet is a module built into React Native that allows us to create immutable stylesheet references. We can pass regular style objects into the create() method, and the module will freeze the objects, and assign each one an ID. This has two benefits: it allows us to avoid creating a new style object every render pass (which could lead to degradation of render performance), and it allows us to send the object across the asynchronous bridge only once (since these style objects map directly to native styles, they need to be passed across). The key tradeoff with this method is that recomputing styles based on external criteria (like screen rotation or even a user-selected viewing mode) needs some infrastructure built to determine which styles to use. If objects were passed in "raw" they could be recomputed on the fly every time, based on arbitrary criteria
What is the InteractionManager and how is it used? Why is it important?
The InteractionManager is the native module responsible for deferring the execution of a function until an "interaction" has finished. We can call InteractionManager.runAfterInteractions(() => {...}) to handle this deferral. We can also register our own interactions. InteractionManager is very important because React Native has two threads. There is a JavaScript UI thread which handles drawing updates to the screen, and another thread used for all tasks not on the UI thread. Since there is only one thread for making UI updates, it can get overloaded and drop frames, especially during things like navigation screen animations. We use the InteractionManager to ensure that our function is executed after these animations occur so that we do not drop frames on the UI thread. Trying to draw a new screen while it is being animated is often too much for the thread to handle.
What is the function of a StyleSheet.create?
The function of StyleSheet.create() in React Native is to ensure the immutability and opaqueness of the values. They are used for sending the style through the bridge only once. Hence, they help to avoid the passing of a new style object.
List the steps to avoid Props drilling
The given steps can be used to avoid props drilling: React Context API Composition Render props HOC MobX or Redux
How to make your React Native app feel smooth on animations ?
The primary reason and an important one why well-built native apps feel so smooth are by avoiding expensive operations during interactions and animations. React Native has a limitation that there is only a single JS execution thread, but you can use InteractionManager to make sure long-running work is scheduled to start after any interactions/animations have completed.
What's the real cause behind performance issues in React Native ?
The real cause behind React Native performance issues is that each thread (i.e Native and JS thread) is blazingly fast. The performance bottleneck in React Native app occurs when you're passing the components from one thread to another unnecessarily or more than required. A major thumb rule to avoid any kind of performance-related issue in React Native is to keep the passes over the bridge to a minimum. • Native thread built for running Java/ Kotlin, Swift/ Objective C • Javascript thread is the primary thread that runs everything from javascript-based animations to other UI components • The bridge as the name suggests acts as an intermediate communication point for the native and JS thread
What is meant by the state in the React component?
The state is another way of modifying a react component apart from the props function. Unlike props, the state value of React component changes in the component's life cycle. The react component's state value should not be changed directly. We should use the setState method of the React framework to change the state of a component.
List the steps of the working of Virtual DOM.
The virtual DOM representation re-renders the entire UI whenever there is a change in the data model. Then it calculates the difference between the previous and new DOM representation. The DOM gets updated once the calculations are completed.
Why is react widely used today?
UI testing is easy. It can integrate with angular and other frameworks easily.has great application performance and overall efficiency.
What is Network Security and SSL Pinning?
Understanding of SSL: SSL (Secure Sockets Layer) and its successor, TLS (Transport Layer Security), are protocols for establishing authenticated and encrypted links between networked computers. SSL/TLS works by binding the identities of entities such as websites and companies to cryptographic key pairs via digital documents known as X.509 certificates. Each key pair consists of a private key and a public key. The private key is kept secure, and the public key can be widely distributed via a certificate. Understanding of pinning Pinning is an optional mechanism that can be used to improve the security of a service or site that relies on SSL Certificates. Pinning allows specifying a cryptographic identity that should be accepted by users visiting site/app Why do we need SSL pinning? One of the inherent risks to the SSL ecosystem is mis-issuance. This is when an unauthorized certificate is issued for a domain/host you control. This can happen with both public and private PKIs (Public Key Infrastructure) How is SSL pinning used in Mobile applications? When mobile applications communicate with the server, they typically use SSL to protect the transmitted data against tampering. By default SSL implementations used, apps trust any server with a certificate trusted by the Operating systems trust store, This store is a list of certificate authorities that are shipped with the operating system. With SSL pinning, however, the application is configured to reject all but one or few predefined certificates, whenever the application connects to a server, it compares the server certificate with the pinned certificate(s) , if and only if they match the server is trusted and SSL connection is established.
What strategy would you use to optimize a large list of items on FlatList?
Use PureComponent on renderItem with bind methods Add keyExtractor property Add pagination Define getItemLayout Define removeClippedSubviews true
What is justifyContent used for?
Used to determine how should elements be distributed inside the container 'center','flex-start','flex-end','space-around','space-between'
What is alignItems used for?
Used to determine how should elements be distributed inside the container along the secondary axis (opposite of flexDirection) center','flex-start','flex-end','stretched'
What is flexDirection used for?
Used to specify if elements will be aligned vertically or horizontally Values 'column' and 'row'
How does rendering work in react?
Uses the render function and returns an element that represents a DOM component.
What is virtual DOM?
Virtual DOM is real DOM's representation. And it is a lightweight JavaScript object. This step comes in between calling the render function and displaying the elements on the screen. It is like a node tree that makes the list of elements, attributes, and content into objects and properties. A node tree of React components is created by the render function, and then it's updated as per the changes in the data model.
What is virtual DOM?
Virtual Dom is a simple JavaScript object that is the the exact copy of the corresponding real Dom
What are animations and their types in React Native?
We can manipulate the images by using animations to make them appear as moving objects. For greater user experience in the application, extra effects can be added in React Native animations. It can be used with React Native API, Animated.decay, Animated.parallel, and Animated.stagger. React Native provides the given two types of animations: Animated- We use this API for controlling specific values. It provides the start and stops methods to control the animation execution on the basis of time. LayoutAnimated- We use this API for animating the global layout transactions.
What happens when you call SetState?
When you call SetState in React, the object you passed into it will be merged into the current state of the component. This triggers something called reconciliation. Reconciliation aims to update the user interface in the most efficient way possible. React does this by constructing a tree of React elements and compare it to the previous element tree. This shows React the exact changes that occurred so React can make updates in the necessary places.
Do you know how can you detect memory leaks on the app?
Xcode and Android studio provide tools to track the memory used by an app. These tools can be used to test the app on both devices and simulators.
Can apps for Android and iOS behave or look different?
Yes! However, it comes at a cost as different code needs to be written for each of the platforms. But even then, it is relatively much cheaper than building 2 native apps. React Native has been developed in such a way that the iOS and Android logic is different. So the platforms can still share their functionality even when they look or behave differently.
Are there any default props available in React Native? What are they used for?
Yes, default props are available in React Native. The default props value is used by the component in case the props value doesn't pass.
Describe how to re-render a FlatList
You can re-render a FlatList by using the extraData property When we pass extraData={this.state} to the FlatList, we ensure it'll re-render itself when the selected state changes. Since FlatList is also a PureComponent, we need to set this prop so it knows to re-render items.
How do you debug React apps and what tools can you use?
You can use Developer menu Chrome DevTools, React Developer Tools, React Native Debugger, React Native CLI
What are states in react?
data or objects that control component behavior and rendering.
Build a React app that does nothing except say "Hello World!"
import React from "react"; import { Text, View } from "react-native"; const HelloWorldApp = () => { return ( <View style={{ flex: 1, justifyContent: "center", alignContent: "center", }}> <Text>Hello World!!</Text> </View> ) } export default HelloWorld;
Name at least one style property that can increase tappable area around an element
padding (and also paddingVertical, ...Horizontal, ...Left, ...Right, ...Top, ...Bottom) minHeight and minWidth hitSlop
Explain about Timers available in React Native app
setInterval, clearInterval • The setInterval method is used to create a loop of a code running after a specific time interval as the second parameter specifies. • clearInterval is used to stop the interval. setTimeout, clearTimeout • setTimeout is used to schedule a piece of code to run at a specific scheduled time. • clearTimeout is just used to clear that timer. setImmediate, clearImmediate • setImmediate calls or execute the function as soon as possible. • clearImmediate cancels the immediate actions set by setImmediate. requestAnimationFrame, cancelAnimationFrame • requestAnimationFrame updates an animation before the next one. • cancelAnimationFrame cancels the functions set by requsetAnimationFrame.
How does React Native differ from other mobile app development frameworks?
• Most other alternatives, such as ionic and Cordova run web apps. At the same time, React Native app runs a real mobile application and not a web app. • It provides better performance than others as the React Native app gets converted into machine code running on mobile. • React Native apps are relatively much closer to Native app development than the other Javascript frameworks. • Mobile apps developed by React Native have a smaller bundle size.
Can you provide some ideas on how to prevent memory leaks in your app?
• Release timers/listeners added in componentDidMount • Handle closure scope
How Different is React-native from ReactJS ?
• Usage Scope ReactJs - React is a JavaScript library for building Responsive User Interfaces for Building Web Application. React Native - It is a framework for creating mobile applications with a native feel. • Syntax Both React and React Native uses JSX (JavaScript XML) syntax but React uses html tags like <div> <h1> <p> etc while React Native uses <view> <text> etc. • Animation And Gestures React uses CSS animations on a major scale to achieve animations for a web page while The recommended way to animate a component is to use the Animated API provided by React-Native. • Routing Mechanism React uses a react-router for routing and does not have any inbuilt routing capabilities but React Native has a built-in Navigator library for navigating mobile applications.
List down some of the steps to optimize the application.
• Use Proguard to minimize the application size.(It does this by stripping parts of the React Native Java bytecode (and its dependencies) that your app is not using) • Create reduced-sized APK files for specific CPU architectures. When you do that, your app users will automatically get the relevant APK file for their specific phone's architecture. This eliminates the need to keep JSCore binaries that support multiple architectures and consequently reduces the app size. • Compress images and other graphic elements. Another option to reduce image size is using file types like APNG in place of PNG files. • Don't store raw JSON data, eIther we need to Compress it or convert it into static object IDs. • Optimize native libraries. • Optimize the number of state operations and remember to use pure and memoized components when needed • Use Global State wisely for example worst-case scenario is when state change of single control like TextInput or CheckBox propagates render of the whole application. Use libraries like Redux or Overmind.js to handle your state management in a more optimized way. • Use key attribute on list items, it helps React Native to pick which list to update when rendering a long list of data • Use VirtualizedList, FlatList, and SectionList for large data sets. • Clear all the active timers which may lead to heavy memory leakage issues.
List some ways you can optimize an application
•Compress or convert our raw JSON data instead of just storing it •Make reduced-sized APK files for CPU architectures •Optimize native libraries and the number of state operations •Use key attributes on list items •Compress images and other graphic elements •Use Proguard to minimize app size and strip parts of our bytecode along with its dependencies