« React-Native Interview Questions

What Is The Second Argument That Can Optionally Be Passed To Setstate And What Is Its Purpose?

Answer: A callback function which will be invoked when setState has finished. setState is asynchronous, which is why it takes in a second callback function.

1this.setState({ username: 'anish' }, () =>
2 console.log('setState has finished and the component has re-rendered.')
3);

What Are Keys In React And Why Are They Important?

Answer: Keys are what help React keep track of what items have changed, been added, or been removed from a list. It’s important that each key be unique among siblings. Part of this reconciliation process is performing a diff of a new element tree with the most previous one. Keys make this process more efficient when dealing with lists because React can use the key on a child element to quickly know if an element is new or if it was just moved when comparing trees. And not only do keys make this process more efficient, but without keys, React can’t know which local state corresponds to which item on move.

1return (
2 <ul>
3 {this.state.todoItems.map(({ task, uid }) => {
4 return <li key={uid}>{task}</li>;
5 })}
6 </ul>
7);

What Happens When You Call setState?

Answer: The first thing React will do when setState is called is merge the object you passed into setState into the current state of the component. This will kick off a process called reconciliation. The end goal of reconciliation is to, in the most efficient way possible, update the UI based on this new state.

To do this, React will construct a new tree of React elements (which you can think of as an object representation of your UI). Once it has this tree, in order to figure out how the UI should change in response to the new state, React will diff this new tree against the previous element tree. By doing this, React will then know the exact changes which occurred, and by knowing exactly what changes occurred, will able to minimize its footprint on the UI by only making updates where absolutely necessary.

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.

What is wrong for querying a native API?

The value of calling NativeModules will always be an unresolved Promise. It’s important to remember that the bridge that connects JavaScript and native code is asynchronous. We can either receive results from this side by passing in a callback or by returning a Promise. In this case, we need to append a then() call to NativeModules call.

Are compile-to-JS libraries like TypeScript or ClojureScript compatible with React Native? Why or why not?

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 web- or Node.js-specific dependencies, it will run in React Native.

How React Native load data from server?

React Native provides the Fetch API which deals networking needs.

1fetch('https://mywebsite.com/mydata.json');

What is the storage system in React Native?

React Native uses AsyncStorage class to store data in key-value pair which is global to all app. AsyncStorage is a JavaScript code which is a simple, unencrypted, asynchronous and persistent.

Using AsyncStorage class, you must have a data backup, and synchronization classes as data saved on the device is not permanent and not encrypted.

How React Native handle different screen size?

Flexbox is designed to provide a consistent layout on different screen sizes. It offers three main properties:

  • flexDirection
  • justifyContent
  • alignItems

PixelRatio exists in the official documentation with the definition such that we can get access to the device pixel density by using PixelRatio class. We will get a higher resolution image if we are on a high pixel density device. An ethical principle is that multiply the size of the image we display by the pixel ratio.

Dimensions easily handle different screen sizes and style the page precisely. It needs to write the code only once for working on any device.

How To Handle Multiple Platforms?

It provides the ways using which you can easily organize your code and separate it by platform:

Platform module to detect the platform in which the app is running and

platform-specific file extensions to load the relevant platform file.

What is Style?

The style prop is a plain JavaScript object use to making style of React Native application.

What are “props” and “state”?

“Props” and “state” are both plain JavaScript objects used to control data inside the components.

props :

  • Immutable parameters -> Unchangeable inside the component.
  • Set by their parent and fixed for the whole lifetime of a component.

state :

  • Mutable parameters -> Changeable inside the component.
  • Get handled within the container component.
  • Can’t be accessed and modified outside the component.

What does a react native packager do?

A react native packager does a few things:

  • It combines all JavaScript code into a single file
  • It translates any JavaScript code that your device don’t understand (e.g., JSX or some of the newer JS syntax)
  • It converts assets like PNG files into objects that can be displayed by an Image

What are refs in React? When to use Refs?

Refs are escape hatch that provides a direct way to access DOM nodes or React elements created in the render method.

Refs get in use when

  • To manage focus, text selection, or media playback
  • To trigger imperative animations
  • To integrate with third-party DOM libraries

Describe HOC.

HOC (High Order Components) in React is the functional programming methodology for reusing component logic.

It takes a component as an argument and returns a new component.

It is a pattern evolved from React’s compositional nature to decompose the logic into simpler and smaller reusable functions.

1function simpleHOC(WrappedComponent) {
2 return class extends React.Component {
3 render() {
4 return <WrappedComponent {...this.props} />;
5 }
6 };
7}
8
9const NewComponent = simpleHOC(Dog);
10
11<NewComponent />;
12
13import React, { useContext, useEffect } from 'react';
14import { Route, Redirect } from 'react-router-dom';
15import AuthContext from '../../context/auth/authContext';
16
17const PrivateRoute = ({ component: Component, ...rest }) => {
18 const authContext = useContext(AuthContext);
19 const { loadUser, isAuthenticated } = authContext;
20 useEffect(() => {
21 loadUser();
22 // eslint-disable-next-line
23 }, []);
24 if (isAuthenticated === null) {
25 return <></>;
26 }
27 return (
28 <Route
29 {...rest}
30 render={(props) =>
31 !isAuthenticated ? <Redirect to='/login' /> : <Component {...props} />
32 }
33 />
34 );
35};
36export default PrivateRoute;

What is the point of the relationship between React Native and React?

React is a JavaScript library. React Native is a framework based on React that use JavaScript for building mobile applications. It uses React to construct its application UI and to define application business logic. React updates a real DOM by tree diffing and allows React Native to work.

What is Virtual DOM and how it works in React Native?

Virtual Dom is an in-memory tree representation of the real DOM with lightweight elements.

Virtual DOM lists elements and their attributes and content. It renders the entire UI whenever any underlying data changes in React Native. Due to which React differentiates it with the previous DOM and a real DOM gets updated.

Which node_modules will run in React Native? How to test for this?

In React Native, node_modules as any pure JavaScript library that does not rely on Node.js runtime modules, and does not rely on web-specific concepts like window.location.pathname will run fine. But be conscious as there exists no way to test for this with Babel- it doesn’t scan these libraries for offending dependencies. A module that uses window.location.pathname may fail at runtime in a different unexpected place.

Why React Native use Redux?

Redux is a standalone state management library that React Native use to simplify data flow within an app.

Differentiate between the React component and the React element.

React component is a class or function that accepts input and returns a React element while React element displays the look of React Component Instance to be created.

Why React Native has very clear animations?

The animated API of React Native was designed as serializable so that users can send animations to native without going through the bridge on every frame. Once the animation starts, a JS thread can be blocked, and the animations will still run fluently. As the code converted into native views before rendering, the animations in React native will run smoothly, and the users get bright 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.:

1Animated.timing(new Animated.Value(0), {
2 useNativeDriver: true,
3 toValue: 100,
4 duration: 100,
5}).start();

This will serialize the operation and send it to the native side before starting it.

What is the difference between React and React Native?

  • React is a JavaScript library while React native is a framework based on React.
  • js is used for building UI and web applications while React Native is used for creating cross-platform native mobile apps.

For what purpose is XHR module used in React Native?

XHR module implements XMLHttpRequest to post data on the server.

How many threads run in React Native?

There are two threads run in React Native:

  • JavaScript thread
  • Main UI thread

How to store sensitive content in React Native apps?

What are NativeModules in React Native??

1public class HelloPTPackage implements ReactPackage {
2 @NonNull
3 @Override
4 public List<NativeModule> createNativeModules(@NonNull ReactApplicationContext reactApplicationContext) {
5 List<NativeModule> modules = new ArrayList<>();
6
7 modules.add(new HelloPTModule(reactApplicationContext));
8
9 return modules;
10 }
11
12 @NonNull
13 @Override
14 public List<ViewManager> createViewManagers(@NonNull ReactApplicationContext reactApplicationContext) {
15 return Collections.emptyList();
16 }
17}
18
19
20public class HelloPTModule extends ReactContextBaseJavaModule {
21
22 public HelloPTModule(@Nullable ReactApplicationContext reactContext) {
23 super(reactContext);
24 }
25
26 @NonNull
27 @Override
28 public String getName() {
29 return "HelloPT";
30 }
31
32 @ReactMethod
33 public void sayHello(String name, Callback cb) {
34 try {
35 String hello = "Hello " + name;
36 cb.invoke(null, "chutspp");
37 } catch (Exception err) {
38 cb.invoke(err, null);
39 }
40 }
41}
42
43@Override
44protected List<ReactPackage> getPackages() {
45 @SuppressWarnings("UnnecessaryLocalVariable")
46 List<ReactPackage> packages = new PackageList(this).getPackages();
47 // Packages that cannot be autolinked yet can be added manually here, for example:
48 // packages.add(new MyReactNativePackage());
49 packages.add(new HelloPTPackage());
50 return packages;
51}
52
53HelloPT.sayHello('Aman', (err, msg) => {
54 if (err) {
55 console.log(err);
56 return;
57 }
58 console.log(msg);
59});
60
61const {HelloPT} = NativeModules;

What is StackTrace

How to optimize React Native apps?

What are RamBundles in React-Native?

How to store offline data in React Native apps?

What is Error Boundary??

1class ErrorBoundary extends React.Component {
2 constructor(props) {
3 super(props);
4 this.state = { hasError: false };
5 }
6
7 static getDerivedStateFromError(error) {
8 // Update state so the next render will show the fallback UI.
9 return { hasError: true };
10 }
11
12 componentDidCatch(error, errorInfo) {
13 // You can also log the error to an error reporting service
14 logErrorToMyService(error, errorInfo);
15 }
16
17 render() {
18 if (this.state.hasError) {
19 // You can render any custom fallback UI
20 return <h1>Something went wrong.</h1>;
21 }
22
23 return this.props.children;
24 }
25}

What is Flexbox in React Native?


How can you keep animations from being blocked on the JavaScript thread? Describe how this works and explain some of the limitations.

  • By adding useNativeDriver: true to the animation options
  • It works by passing the animation to the native thread where it will not be blocked by the JavaScript thread
  • This will work on non-layout properties like opacity and transform, but will not work on things like flex, or position

What is a Fragment and why would you use one?

  • A fragment is a way of grouping JSX elements together without adding to the render tree by wrapping them in an additional view.
  • A good example of where to use a fragment is in a dedicated component of a screen where no additional container styling is needed.
  • The benefits of using a fragment is less complex styling in some cases and less complex rendering.

What does StyleSheet.create do?

StyleSheet.create method ensures that values are immutable and opaque, they are also only created once.


What are hooks and when would you use them?

Hooks is a way to use stateful logic, effects, etc outside of a class.

A hook is a useful way to share stateful logic across multiple functional components, examples include: A modal’s open/closed state, Form state, and Subscribing to events


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

Can you provide some ideas on how to prevent memory leaks in your app?

  • Release timers/listeners added in componentDidMount

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.


Name at least one style property that can increase tappable area around an element

padding


What is Props Drilling?

Props Drilling is a term that refers to the process of passing data from the parent component to the child component, although other components possess the props in between only to send it down the chain.


Describe Timers in React Native Application.

setTimeout, and clearTimeout There may be business requirements to execute a specific piece of code after a specified amount of time or after a delay. In such circumstances, setTimeout can be used, while clearTimeout merely clears the timer that has been established.

clearInterval, setInterval setInterval is a method that invokes a function or executes code at defined time intervals, as provided by the second parameter. A function or block of code bound to an interval runs until it is terminated. The clearInterval() method can be used to end an interval.

setImmediate, clearImmediate The function or execution is called as soon as possible. clearImmediate is used to cancel the immediate actions defined by setImmediate().

cancelAnimationFrame, requestAnimationFrame It is the most common approach to creating animations.


Explain different threads in react native.

React Native currently employs three threads:

MAIN/UI Thread – The main application thread on which your Android/iOS app runs. The main thread has access to the application's UI and can update it.

Shadow Thread — This is a background thread that can calculate layouts built with the React framework in React Native.

JavaScript Thread - This thread executes the primary Javascript code.


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

How can you fetch data from a local JSON file in React Native?

1const customData = require('./customData.json');
1import * as data from './example.json';
2const word = data.name;
3console.log(word);

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.

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


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.


How do you call a Web API in React Native?

1fetch('http://**sampleurl**', {
2 method: 'POST',
3 headers: {
4 Accept: 'application/json',
5 'Content-Type': 'application/json',
6 },
7 body: JSON.stringify({
8 username: 'educative1',
9 password: 'educative987',
10 }),
11});

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.

1<FlatList
2 data={data}
3 style={FlatListstyles}
4 extraData={this.state}
5 renderItem={this._renderItem}
6/>

How do you debug React apps and what tools can you use?

Toggle Inspector toggles the inspector interface so we can inspect UI elements and their properties

Show Perf Monitor: monitors performance

React Developer Tools To use React’s Developer Tools, you have to use the desktop app. These tools allow you to debug React components and styles.

React Native Debugger If you’re using Redux in your React app, this is a good debugger for you. It’s a desktop app that integrates Redux’s and React’s developer tools in one app.

Flipper


What is Redux and when should you use it?

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 JSX?

JavaScript XML, or JSX, is a XML/HTML template syntax used by React.


What is wrong with this code for querying a native API?

1lass GyroJs {
2 setGyroPosition(pos) {
3 if (pos === null || typeof pos === 'undefined') {
4 throw new Error('The position must be defined');
5 }
6 this.pos = pos;
7 }
8 constructor() {
9 const gyroscopePosition = NativeModules.MyGyroModule.gyroPosition();
10 this.setGyroPosition(gyroscopePosition);
11 }
12}

This code will always throw an error because the value of gyroscopePosition will always be an unresolved Promise. It’s important to remember that the bridge that connects JavaScript and native code is asynchronous. We can either receive results from this side by passing in a callback, or by returning a Promise. In this case, we need to append a then() call to the gyroPosition() call and set the position inside it.


Explain some of the fundamental tradeoffs between building with React Native and building a “true” native app

React Native makes sense when a team is building a product that does not need extremely high performance. The limitations of the asynchronous bridge are a bottleneck for things like 3D games, and games with lots of particle updates. Apps that rely on deep interactions with low-level APIs, or need large amounts of native code, might be easier to build as native apps.

React Native makes sense when an existing team is already proficient in JavaScript and/or has an existing React application built on the web or another platform.


What are React Hooks?

They let you use state and other React features without writing a class. With Hooks, you can extract stateful logic from a component so it can be tested independently and reused.


What is React Native?

React Native is a mobile app development framework that enables the development of multi-platform Android and iOS apps using native UI elements. It is based on the JavaScriptCore runtime and Babel transformers. With this setup react native supports new JavaScript (ES6+) features, e.g. arrow functions, async/await etc.


FlatList vs ScrollView

ScrollView: The ScrollView Component is an inbuilt react-native component that serves as a generic scrollable container, with the ability to scroll child components and views inside it.

The ScrollView is a generic scrolling container that can contain multiple components and views. The scrollable items need not be homogeneous, and you can scroll both vertically and horizontally (by setting the horizontal property).

ScrollView renders all its react child components at once, but this has a performance downside.

When to use ScrollView?

ScrollView loads all the content, i.e. the data to be displayed on screen all at once. This is done immediately after the component is loaded. Thus, the entire content (data list) is mounted altogether. Now if this data list contains many items, it would automatically cause performance issues. So it is not preferred to use ScrollView if you have a hundred or a thousand items to be displayed on the screen. It is used when you have fewer data items on the list of a limited size.

Flatlist: The FlatList Component is an inbuilt react-native component that displays similarly structured data in a scrollable list. It shows only those elements that are currently being displayed on the screen.

FlatList, on the other hand, has a better solution for this problem; it will mount 10 items (by default) to the screen, and as the user scrolls the view, other items will mount. It's a significant advantage to use FlatList instead of ScrollView.

When to use FlatList?

As opposed to the ScrollView, the FlatList renders only those elements that are currently being displayed on the screen (default: 10 items). Thus, it does not have any impact on the performance of the application. So, it is preferable to use the FlatList Component to display a large list of data.

ScrollView renders all its react child components at once, but this has a performance downside. FlatList renders items lazily, when they are about to appear, and removes items that scroll way off-screen to save memory and processing time.

Component state is not maintained with the FlatList component but component state is maintained with ScrollView This is due to the fact that ScrollView renders all the children in one go and maintains them. Meanwhile, FlatList unmounts components once they are way off the screen and recreates them from scratch once the item comes back from screen (thus state is lost).


Explain the use of Flexbox in React Native?

  • To accommodate different screen sizes, React Native offers Flexbox support.
  • To achieve the desired layout, flexbox offers three main properties − flexDirection, justifyContent and alignItems.

Live reloading vs Hot reloading

  • Live reloading reloads or refreshes the entire app when a file changes. For example, if you were four links deep into your navigation and saved a change, live reloading would restart the app and load the app back to the initial route.
  • Hot reloading only refreshes the files that were changed without losing the state of the app. For example, if you were four links deep into your navigation and saved a change to some styling, the state would not change, but the new styles would appear on the page without having to navigate back to the page you are on because you would still be on the same page.

props vs state

props : are immutable and are set by the parent and they are fixed throughout the lifetime of a component.

state : is mutable. This means that state can be updated in the future while props can’t. we can initialize state in the constructor, and then call setState when we want to change it.


How do you style a component in react native?

With React Native, you style your application using JavaScript.

All of the core components accept a prop named style. The style names and values usually match how CSS works on the web, except names are written using camel casing, e.g. backgroundColor rather than background-color.

The style prop can be a plain old JavaScript object. That's the simplest and what we usually use for example code.

You can also pass an array of styles - the last style in the array has precedence, so you can use this to inherit styles.

As a component grows in complexity, it is often cleaner to use StyleSheet.create to define several styles in one place.

1const styles = StyleSheet.create({
2 container: {
3 borderRadius: 4,
4 borderWidth: 0.5,
5 borderColor: '#d6d7da',
6 },
7 title: {
8 fontSize: 19,
9 fontWeight: 'bold',
10 },
11 activeTitle: {
12 color: 'red',
13 },
14});
15
16<View style={styles.container}>
17 <Text style={[styles.title, this.props.isActive && styles.activeTitle]} />
18</View>;

How is flexbox different in React Native and browser?

Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row, and the flex parameter only supporting a single number.


What is View and how important is it?

  • View is the most fundamental component for building a UI in react native.
  • View is a container that supports layout with flexbox, style, some touch handling, and accessibility controls.
  • View maps directly to the native view equivalent on whatever platform React Native is running on, whether that is a UIView, div, android.view, etc.

What is the difference between ShadowDOM and VirtualDOM

Virtual DOM

Virtual DOM is about avoiding unnecessary changes to the DOM, which are expensive performance-wise, because changes to the DOM usually cause re-rendering of the page. Virtual DOM also allows to collect several changes to be applied at once, so not every single change causes a re-render, but instead re-rendering only happens once after a set of changes was applied to the DOM.

Shadow DOM

Shadow dom is mostly about encapsulation of the implementation. A single custom element can implement more-or-less complex logic combined with more-or-less complex DOM. An entire web application of arbitrary complexity can be added to a page by an import and

1<body>
2 <my-app></my-app>
3</body>

but also simpler reusable and composable components can be implemented as custom elements where the internal representation is hidden in the shadow DOM like.

1<date-picker></date-picker>

What is the significance of keys in ReactJS

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.


What JavaScript engine does React native use?

React Native uses two engines.

JavaScriptCore engine is used primarily, which Safari browser runs on.

V8 engine is used when using Chrome debugging. All JavaScript code runs within Chrome itself, communicating with native code via WebSockets.


Images From Hybrid App's Resources

If you are building a hybrid app (some UIs in React Native, some UIs in platform code) you can still use images that are already bundled into the app.

For images included via Xcode asset catalogs or in the Android drawable folder, use the image name without the extension:

1<Image source={{ uri: 'app_icon' }} style={{ width: 40, height: 40 }} />
1<Image
2 source={{ uri: 'asset:/app_icon.png' }}
3 style={{ width: 40, height: 40 }}
4/>

These approaches provide no safety checks. It's up to you to guarantee that those images are available in the application. Also you have to specify image dimensions manually.


React Native Image Performance

  • Loading Static Assets: With static assets I’ve found noticeable performance gains by simply loading assets from the app package (images included via Xcode asset catalogs or in the Android drawable folder) vs the JavaScript package. I found this while trying to load 350 icon assets in the same view (very uncommon). I was seeing nearly a 15 second render time for the view when loading the assets from the JavaScript package. Once I moved all the assets to the app package my render time went down to 10 milliseconds. When loading assets from the Javascript package, React Native requires the asset file from the package and then sends it across the bridge to the UI Layer to be rendered. When the asset is already within the app package, React can just tell the UI layer to render the specific image without having to require or transfer the image data across the bridge.
  • Asset File Type and Size : When working with assets in react native you should take a similar approach as you would on the web. We want to use the smaller file size as possible. When we are loading assets from the JavaScript package those files are being sent across the bridge. So the larger those files are the longer it’s going to take for them to transfer across and be rendered on the screen. To achieve the smallest file size I do a few things. When possible I use JPEG files. They will naturally be a smaller file size as they can be compressed down further. Unfortunately with a lot of UI stuff you need transparency so you have no choice but to use PNG.

Image VS FastImage

React Native's Image component handles image caching like browsers for the most part. If the server is returning proper cache control headers for images you'll generally get the sort of built in caching behavior you'd have in a browser. Even so many people have noticed:

  • Flickering.
  • Cache misses.
  • Low performance loading from cache.
  • Low performance in general.

FastImage is an Image replacement that solves these issues. FastImage is a wrapper around SDWebImage (iOS) and Glide (Android).


Why redux-thunk??

Thunk doesn’t interfere with the action until it returns a function. Thunk allows us to dispatch actions manually, which gives us the power to incorporate some logic or run some asynchronous code before dispatching an action.


Why redux-saga??

Redux Saga is an alternative approach to the organization of side effects. Instead of dispatching functions processed by Redux Thunk you create saga and write all the logic of event stream processing. Unlike thunks that are carried out when you dispatch them, sagas run in the background right after the app is launched. Sagas observe all actions that the store dispatches and decide what to do with them.


Why middlewares in react-native

Middleware allows for side effects to be run without blocking state updates. We can run side effects (like API requests) in response to a specific action, or in response to every action that is dispatched (like logging). There can be numerous middleware that an action runs through before ending in a reducer.


Draw grid in react-native

  1. The old fashioned way with flexbox
  2. Using FlatList with a numColumns prop
  3. Using a flexWrap container with fixed-width items

How to improve the performance of a React Native app

  • Avoid Use of ScrollView to Render Huge Lists.
  • Avoid Passing Inline Functions as Props
  • Scale and Resize Images
  • Cache Images
  • React Native offers as a core component
  • Use nativeDriver With the Animated Library
  • Avoid Excessive Use of Higher-Order Components

Avoid Rendering Overhead and Unnecessary Renders

  1. Memoization using useMemo() and UseCallback() Hooks

Memoization enables your code to re-render components only if there’s a change in the props. With this technique, developers can avoid unnecessary renderings and reduce the computational load in applications.

React provides two Hooks to implement memoization:

  • useMemo()
  • UseCallback()

These Hooks reduce re-renderings by caching and returning the same result if the inputs are the same without any computations. When the inputs change, the cache gets invalidated and the new component state gets rendered.

useMemo()

if we use the useMemo() Hook, we can avoid component re-rendering if the inputs are the same and save the result in the cache.

1useMemo(() => multiply(x, y), [x, y]);

UseCallback()

UseCallback() is another React Hook to implement memoization. But, unlike useMemo(), it does not cache the result. Instead, it memoizes the callback function provided to it.

1import { useCallback } from 'react';
2export function MyParent({ term }) {
3 const onClick = useCallback(event => {
4 console.log('Clicked Item : ', event.currentTarget);
5 }, [item]);
6 return (
7 <Listitem {item} onClick={onClick} />
8 );
9}
  1. API Call Optimization with React Query

It’s common to use the useEffect() Hook for asynchronous data fetching operations in React applications. However, useEffect() runs and fetches data on each render, and in most situations, it keeps loading the same data.

As a solution, we can use the React Query library to cache the response data. When we make an API call, React Query will first return the data from the cache before continuing with the request. Then, it will retrieve the data from the server, and if there is no new data available, it will prevent the component from re-rendering.

1import React from 'react';
2import { useQuery } from 'react-query';
3import axios from 'axios';
4
5async function fetchArticles() {
6 const { data } = await axios.get(URL);
7 return data;
8}
9
10function Articles() {
11 const { data, error, isError, isLoading } = useQuery(
12 'articles',
13 fetchArticles
14 );
15
16 if (isLoading) {
17 return <div>Loading...</div>;
18 }
19 if (isError) {
20 return <div>Error! {error.message}</div>;
21 }
22 return <div></div>;
23}
24export default Articles;
  1. Creating Memoized Selectors with Reselect

Reselect is a third-party React library for creating memorized selectors. It is commonly used with Redux stores and has amazing features to reduce unnecessary re-renderings.

  • Reselect selectors are capable of computing derived data.
  • Reselect selectors do not recompute unless their arguments are changed.
  • They can be used as inputs to other selectors.

Reselect provides an API named createSelector, and it can generate memoized selector functions.

  1. Replace useState() with useRef()

useState() Hook is widely used in React applications to re-render the components on state changes. However, there are scenarios where we need to track state changes without re-rendering the components.

But, if we use the useRef() Hook, we can track the state changes without causing component re-renderings.

1function App() {
2 const [toggle, setToggle] = React.useState(false);
3 const counter = React.useRef(0);
4 console.log(counter.current++);
5 return <button onClick={() => setToggle((toggle) => !toggle)}>Click</button>;
6}
7ReactDOM.render(
8 <React.StrictMode>
9 <App />
10 </React.StrictMode>,
11 document.getElementById('mydiv')
12);
  1. Using React Fragments

React requires wrapping the components with a single parent element. Though it’s not directly about re-rendering, have you known that it affects the overall component rendering time?

As a solution, you can use React Fragments to wrap the components, and it will reduce the load on the DOM, resulting in faster rendering times and decreased memory usage.

1const App= () => {
2 return (
3 <React.Fragment><p>Hello<p/><p>World<p/></React.Fragment>
4 );
5};

Uses of useRef

  • The useRef Hook allows you to persist values between renders.
  • It can be used to store a mutable value that does not cause a re-render when updated.
  • It can be used to access a DOM element directly.

If we tried to count how many times our application renders using the useState Hook, we would be caught in an infinite loop since this Hook itself causes a re-render.

To avoid this, we can use the useRef Hook.

1import { useState, useEffect, useRef } from 'react';
2import ReactDOM from 'react-dom/client';
3
4function App() {
5 const [inputValue, setInputValue] = useState('');
6 const count = useRef(0);
7
8 useEffect(() => {
9 count.current = count.current + 1;
10 });
11
12 return (
13 <>
14 <input
15 type='text'
16 value={inputValue}
17 onChange={(e) => setInputValue(e.target.value)}
18 />
19 <h1>Render Count: {count.current}</h1>
20 </>
21 );
22}
23
24const root = ReactDOM.createRoot(document.getElementById('root'));
25root.render(<App />);

In general, we want to let React handle all DOM manipulation.

But there are some instances where useRef can be used without causing issues.

In React, we can add a ref attribute to an element to access it directly in the DOM.

1import { useRef } from 'react';
2import ReactDOM from 'react-dom/client';
3
4function App() {
5 const inputElement = useRef();
6
7 const focusInput = () => {
8 inputElement.current.focus();
9 };
10
11 return (
12 <>
13 <input type='text' ref={inputElement} />
14 <button onClick={focusInput}>Focus Input</button>
15 </>
16 );
17}
18
19const root = ReactDOM.createRoot(document.getElementById('root'));
20root.render(<App />);

The useRef Hook can also be used to keep track of previous state values.

This is because we are able to persist useRef values between renders.

1import { useState, useEffect, useRef } from 'react';
2import ReactDOM from 'react-dom/client';
3
4function App() {
5 const [inputValue, setInputValue] = useState('');
6 const previousInputValue = useRef('');
7
8 useEffect(() => {
9 previousInputValue.current = inputValue;
10 }, [inputValue]);
11
12 return (
13 <>
14 <input
15 type='text'
16 value={inputValue}
17 onChange={(e) => setInputValue(e.target.value)}
18 />
19 <h2>Current Value: {inputValue}</h2>
20 <h2>Previous Value: {previousInputValue.current}</h2>
21 </>
22 );
23}
24
25const root = ReactDOM.createRoot(document.getElementById('root'));
26root.render(<App />);

What happens in configuration change and process shutdown in react-native app??

I guess as state is in react js and redux so redrawing won't affect anything.


BackHandler API in react-native

The Backhandler API detects hardware button presses for back navigation, lets you register event listeners for the system's back action, and lets you control how your application responds. It is Android-only.

The event subscriptions are called in reverse order (i.e. the last registered subscription is called first).

  • If one subscription returns true, then subscriptions registered earlier will not be called.
  • If no subscription returns true or none are registered, it programmatically invokes the default back button functionality to exit the app.
1import React, { useEffect } from 'react';
2import { Text, View, StyleSheet, BackHandler, Alert } from 'react-native';
3
4const App = () => {
5 useEffect(() => {
6 const backAction = () => {
7 Alert.alert('Hold on!', 'Are you sure you want to go back?', [
8 {
9 text: 'Cancel',
10 onPress: () => null,
11 style: 'cancel',
12 },
13 { text: 'YES', onPress: () => BackHandler.exitApp() },
14 ]);
15 return true;
16 };
17
18 const backHandler = BackHandler.addEventListener(
19 'hardwareBackPress',
20 backAction
21 );
22
23 return () => backHandler.remove();
24 }, []);
25
26 return (
27 <View style={styles.container}>
28 <Text style={styles.text}>Click Back button!</Text>
29 </View>
30 );
31};
32
33const styles = StyleSheet.create({
34 container: {
35 flex: 1,
36 alignItems: 'center',
37 justifyContent: 'center',
38 },
39 text: {
40 fontSize: 18,
41 fontWeight: 'bold',
42 },
43});
44
45export default App;

Alert API in react-native

Launches an alert dialog with the specified title and message.

Optionally provide a list of buttons. Tapping any button will fire the respective onPress callback and dismiss the alert. By default, the only button will be an 'OK' button.

This is an API that works both on Android and iOS and can show static alerts. Alert that prompts the user to enter some information is available on iOS only.

iOS

On iOS you can specify any number of buttons. Each button can optionally specify a style, available options are represented by the AlertButtonStyle enum.

Android

On Android at most three buttons can be specified. Android has a concept of a neutral, negative and a positive button:

  • If you specify one button, it will be the 'positive' one (such as 'OK')
  • Two buttons mean 'negative', 'positive' (such as 'Cancel', 'OK')
  • Three buttons mean 'neutral', 'negative', 'positive' (such as 'Later', 'Cancel', 'OK')

Alerts on Android can be dismissed by tapping outside of the alert box. It is disabled by default and can be enabled by providing an optional Options parameter with the cancelable property set to true i.e.

1{
2 cancelable: true;
3}
1import React, { useState } from 'react';
2import { View, StyleSheet, Button, Alert } from 'react-native';
3
4const App = () => {
5 const createTwoButtonAlert = () =>
6 Alert.alert('Alert Title', 'My Alert Msg', [
7 {
8 text: 'Cancel',
9 onPress: () => console.log('Cancel Pressed'),
10 style: 'cancel',
11 },
12 { text: 'OK', onPress: () => console.log('OK Pressed') },
13 ]);
14
15 const createThreeButtonAlert = () =>
16 Alert.alert('Alert Title', 'My Alert Msg', [
17 {
18 text: 'Ask me later',
19 onPress: () => console.log('Ask me later pressed'),
20 },
21 {
22 text: 'Cancel',
23 onPress: () => console.log('Cancel Pressed'),
24 style: 'cancel',
25 },
26 { text: 'OK', onPress: () => console.log('OK Pressed') },
27 ]);
28
29 return (
30 <View style={styles.container}>
31 <Button title={'2-Button Alert'} onPress={createTwoButtonAlert} />
32 <Button title={'3-Button Alert'} onPress={createThreeButtonAlert} />
33 </View>
34 );
35};
36
37const styles = StyleSheet.create({
38 container: {
39 flex: 1,
40 justifyContent: 'space-around',
41 alignItems: 'center',
42 },
43});
44
45export default App;

Threading Model

The React Native renderer distributes the work of the render pipeline across multiple threads.

React Native renderer is designed to be thread safe. At a high level thread safety is guaranteed by using immutable data structures in the internals of the framework (enforced by C++ const correctness feature). This means that every update in React creates or clones new objects in the renderer instead of updating data structures. This allows the framework to expose thread safe and synchronous APIs to React.

The renderer uses three different threads:

  • UI thread (often called main): The only thread that can manipulate host views.
  • JavaScript thread: This is where React’s render phase is executed.
  • Background thread: Thread dedicated to layout.

View Flattening

View Flattening is an optimization by the React Native renderer to avoid deep layout trees.

The React API is designed to be declarative and reusable through composition. However, in implementation, these qualities of the API lead to the creation of deep React Element Trees, where a large majority of React Element Nodes only affect the layout of a View and don’t render anything on the screen. We call these types of nodes Layout-Only Nodes.

Conceptually, each of the Nodes of the React Element Tree have a 1:1 relationship with a view on the screen, therefore rendering a deep React Element Tree that is composed by a large amount of “Layout-Only” Node leads to poor performance during rendering.

1function MyComponent() {
2 return (
3 <View> // ReactAppComponent
4 <View style={{margin: 10}} /> // ContainerComponent
5 <View style={{margin: 10}}> // TitleComponent
6 <Image {...} />
7 <Text {...}>This is a title</Text>
8 </View>
9 </View>
10 </View>
11 );
12}

view_flattening.png

The View Flattening algorithm is integrated by design as part of the diffing stage of the renderer, which means that we don’t use extra CPU cycles to optimize the React Element Tree flattening these types of views. As the rest of the core, the View flattening algorithm is implemented in C++ and its benefits are shared by default on all supported platforms.

In the case of the previous example, the Views (2) and (3) would be flattened as part of the “diffing algorithm” and as a result their styles will be merged into the View (1):


Create custom hooks

useFetch.js:

1import { useState, useEffect } from 'react';
2
3const useFetch = (url) => {
4 const [data, setData] = useState(null);
5
6 useEffect(() => {
7 fetch(url)
8 .then((res) => res.json())
9 .then((data) => setData(data));
10 }, [url]);
11
12 return [data];
13};
14
15export default useFetch;
16
17import ReactDOM from 'react-dom/client';
18import useFetch from './useFetch';
19
20const Home = () => {
21 const [data] = useFetch('https://jsonplaceholder.typicode.com/todos');
22
23 return (
24 <>
25 {data &&
26 data.map((item) => {
27 return <p key={item.id}>{item.title}</p>;
28 })}
29 </>
30 );
31};
32
33const root = ReactDOM.createRoot(document.getElementById('root'));
34root.render(<Home />);
1import React from 'react';
2
3export default function useDeviceDetect() {
4 const [isMobile, setMobile] = React.useState(false);
5
6 React.useEffect(() => {
7 const userAgent =
8 typeof window.navigator === 'undefined' ? '' : navigator.userAgent;
9 const mobile = Boolean(
10 userAgent.match(
11 /Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile|WPDesktop/i
12 )
13 );
14 setMobile(mobile);
15 }, []);
16
17 return { isMobile };
18}
19
20import React from 'react';
21import useDeviceDetect from '../utils/useDeviceDetect';
22
23function Course() {
24 const { isMobile } = useDeviceDetect();
25
26 return (
27 <>
28 <SEO />
29 {!isMobile && <StickyHeader {...courseData} />}
30 {/* more components... */}
31 </>
32 );
33}
1import React from 'react';
2
3export default function useWindowSize() {
4 const isSSR = typeof window !== 'undefined';
5 const [windowSize, setWindowSize] = React.useState({
6 width: isSSR ? 1200 : window.innerWidth,
7 height: isSSR ? 800 : window.innerHeight,
8 });
9
10 function changeWindowSize() {
11 setWindowSize({ width: window.innerWidth, height: window.innerHeight });
12 }
13
14 React.useEffect(() => {
15 window.addEventListener('resize', changeWindowSize);
16
17 return () => {
18 window.removeEventListener('resize', changeWindowSize);
19 };
20 }, []);
21
22 return windowSize;
23}
24
25import React from 'react';
26import useWindowSize from '../utils/useWindowSize';
27
28function StickyHeader() {
29 const { width } = useWindowSize();
30
31 return (
32 <div>
33 {/* visible only when window greater than 500px */}
34 {width > 500 && (
35 <>
36 <div onClick={onTestimonialsClick} role='button'>
37 <span>Testimonials</span>
38 </div>
39 <div onClick={onPriceClick} role='button'>
40 <span>Price</span>
41 </div>
42 <div>
43 <span onClick={onQuestionClick} role='button'>
44 Question?
45 </span>
46 </div>
47 </>
48 )}
49 {/* visible at any window size */}
50 <div>
51 <span className='primary-button' onClick={onPriceClick} role='button'>
52 Join Now
53 </span>
54 </div>
55 </div>
56 );
57}

closures in javascript

setTimeOut

Handle sending notifications to specific users

handle different screen sizes in react native

How to use eslint in react-native project