Friday, March 1, 2024

Important React Native Efficiency Ideas and Tips — SitePoint

Must read

On this article, we’ll current a complete set of suggestions and techniques designed to empower builders in optimizing their React Native functions, elevating them to peak efficiency, and delivering an unparalleled consumer expertise.

Maximizing the efficiency of React Native functions is essential for guaranteeing a seamless and environment friendly consumer expertise. Sadly, many builders overlook the importance of efficiency optimization, usually prioritizing the performance of their code with out contemplating its impression on velocity and responsiveness.

What units distinctive builders aside is their capability to method coding with a conscious consideration of efficiency implications.

Desk of Contents

Steadiness Animations between the JS Thread and the Fundamental Thread

In any utility, animation is a demanding activity, and this holds true for React Native as properly.

React Native operates with two predominant threads: the JS thread for executing JavaScript code, and the principle thread, which is primarily answerable for rendering the consumer interface and responding to consumer enter.

Animations usually run on the principle thread by default. Nevertheless, a heavy animation workload on the principle thread can result in efficiency points, equivalent to dropped frames.

Let’s contemplate a situation the place you will have a React Native utility displaying a draggable aspect on the display screen (equivalent to a draggable ball). The consumer can drag this aspect across the display screen utilizing contact gestures, and also you purpose to animate its motion easily.

Within the above situation, once you drag the ball across the display screen, the principle thread will likely be busy gathering consumer touches. If we execute animations on the principle thread, it’ll burden it additional. The outcome will probably be dropped frames and efficiency points. In such eventualities, we will shift the animation activity on the JS thread by utilizing the options mentioned under.

Resolution 1: Strive utilizing useNativeDriver

useNativeDriver is a React Native animation property that you should utilize when animating parts in your React Native utility.

When the consumer units this property’s worth to true, the React Native utility will render the animation on the principle thread. Nevertheless, if the principle thread is anticipated to be busy with another activity, you possibly can shift the animation to the JS thread by setting useNativeDriver: false.


Animated.timing(this.state.animatedValue, {
  toValue: 1,
  period: 500,
  useNativeDriver: false, 

Within the code above, React Native will test the useNativeDriver worth and it’ll shift the animation to the JS thread.

You’ll be able to study extra about animation right here.

Resolution 2: Use InteractionManager

There will likely be eventualities the place each the JS thread and the principle thread will likely be busy. For instance, the appliance could also be fetching API knowledge, performing some logic, and rendering it on the UI.

On this scenario, the JS thread is occupied with fetching the info and performing logic, whereas the principle thread is busy displaying the UI. When each threads are engaged, trying to run animations may end up in dropped frames and efficiency points.

In such circumstances, InteractionManager will be utilized. You provoke the animation first. As soon as the animation is accomplished, React Native will name InteractionManager.runAfterInteractions to execute JS code. The JS code will then name the API and show knowledge on the UI.

This method helps keep away from overloading the JS thread with simultaneous execution of JS code and animations.


InteractionManager.runAfterInteractions(() => {

Keep away from Pointless Re-rendering

Avoiding pointless re-renderings in React Native is essential for sustaining optimum efficiency. Each time the app re-renders, the JS thread creates a JS bundle file and passes it by the React Native bridge, which then arms it over to the principle thread.

The extra the appliance re-renders, the extra passes happen between the JS thread and the principle thread, which might degrade the appliance’s efficiency.

Resolution 1: Memoize the element

React.memo is a higher-order element offered by React that’s used for optimizing practical parts by stopping pointless re-renders.

Whenever you wrap a practical element with React.memo, React will memoize the element, that means it’ll solely re-render the element if its props have modified. If the props stay the identical between renders, React will reuse the beforehand rendered outcome, thus avoiding the price of rendering the element once more.


const MyComponent = React.memo((props) => {

Resolution 2: Study to make use of useCallback perform correctly

When a mother or father element units a callback perform for its baby element, at any time when the mother or father element re-renders, the callback perform can be recreated, leading to a brand new perform reference being returned.

Consequently, the kid element perceives this as a change within the callback perform’s worth, prompting it to re-render, even when React.memo is utilized. Due to this fact, the kid element will certainly re-render.

To mitigate this, make the most of useCallback to forestall the recreation of the perform reference on each re-render of the mother or father element.

If you wish to use a callback perform with new state values, the perform needs to be recreated. To recreate the perform with up to date state values, you possibly can make the most of the dependency part in useCallback.

By including state values to the dependency array, as demonstrated within the instance code under, useCallback will recreate the perform solely when the state worth adjustments. Consequently, you’ll receive a brand new perform reference and up to date values because of this.


const memoizedCallback = useCallback(() => {
}, [dependency]);

Resolution 3: Attempt to keep away from updating the native state with Redux state

Updating the state with Redux knowledge may end up in the element rendering twice: first when the Redux knowledge is up to date, and once more when the native state is up to date with Redux state.

By following this method, we will keep away from pointless re-rendering of the element. Due to this fact, attempt to chorus from updating the native state with Redux-updated retailer knowledge.

As a substitute, make the most of Redux retailer values straight within the UI. If calculations are vital earlier than displaying any Redux knowledge initially, then solely use the element state with the Redux state.

Resolution 4: Memoize the perform outcome

Memoize the perform outcome with useMemo. It will execute the perform and retailer the worth in reminiscence.

When the app calls the perform once more, it retrieves the info from the memoized storage as an alternative of executing the whole perform repeatedly. You’ll be able to add dependencies to re-execute the perform and retailer a brand new outcome.


const handleClick = useMemo(() => {
}, [dependency]);

Resolution 5: Keep away from inline features

Keep away from utilizing inline features. As a substitute, use arrow features with useCallback and useMemo to forestall pointless re-rendering.

When a mother or father element re-renders, features are additionally recreated with new references. If we cross any perform as a prop to a baby element, the kid element will even re-render.

To beat this downside, we will use the useCallback perform to forestall perform recreation.

Moreover, by utilizing useMemo, we will keep away from re-rendering the kid element.

Additionally, by utilizing named features as an alternative of inline features, your code turns into extra readable and maintainable.


<Textual content onPress={() => pressed()}>Press Me</Textual content> 
<Textual content onPress={pressed}>Press Me</Textual content> 

The advisable instance above will straight name the perform as an alternative of making another perform.

Optimizing Photos

Optimizing photos can enhance app efficiency. We will make the most of the react-native-compressor npm bundle to cut back the picture dimension for importing and viewing. Moreover, we will use SVG photos to show icons and different photos.

Resolution 1: Use SVG icons and pictures

SVG recordsdata include XML code describing picture/icon paths and features. SVG photos are resolution-independent, permitting them to be scaled to any dimension with out shedding readability.

Since SVG photos are rendered utilizing vector paths moderately than pixel knowledge, they usually eat much less reminiscence when rendered within the utility. This will result in improved picture load efficiency, particularly on gadgets with restricted reminiscence assets.

SVG recordsdata are inclined to have smaller file sizes than raster picture codecs like PNG or JPEG, particularly for easy or geometric graphics. This leads to sooner obtain occasions and reduces the general reminiscence footprint of the appliance.

Resolution 2: Use WebP picture for lossless picture high quality

WebP is a contemporary picture format developed by Google that effectively reduces picture dimension with out compromising high quality. WebP photos are smaller in dimension but keep good high quality, enabling sooner show on screens.

Resolution 3: Cache photos to render sooner

Make the most of caching mechanisms to retailer beforehand loaded photos, decreasing the necessity to fetch photos from the community repeatedly. You’ll be able to cache URL photos utilizing the react-native-fast-image npm bundle. This library will show cached photos instantly on the display screen.

Use Steady NPM Packages

Go for smaller-sized and extra secure npm packages. These packages not solely scale back the scale of your React Native utility but additionally guarantee effectivity as a consequence of their secure codebase.

As a way to determine the precise bundle to your performance, contemplate the next factors from the npm web site:

  1. Examine various kinds of npm packages with the identical performance.
  2. Verify the weekly downloads of the npm bundle. A bundle with extra weekly downloads is preferable.
  3. Verify the npm bundle dimension. A bundle with a smaller dimension will occupy much less area within the challenge, thus decreasing the challenge dimension.
  4. Verify the variety of releases. The next variety of releases signifies energetic upkeep by builders.
  5. Verify the final replace. This helps decide whether or not the bundle remains to be being maintained by somebody.

Following these factors will help in deciding on the precise npm bundle.

Use Stylesheet to the Element

Using the StyleSheet module to model parts presents the benefit of making an object solely throughout the preliminary name. Subsequent calls will reuse the already created model object reference. This method helps scale back the creation of fashion objects for each re-rendering.

Use Flatlist for Efficiency

Use FlatList to render arrays of things as an alternative of utilizing ScrollView with the map perform. FlatList solely renders the objects which are at the moment seen on the display screen, which helps optimize the code by rendering solely the mandatory objects.

Keep away from Reminiscence Leaking

A reminiscence leak is a scenario the place this system doesn’t launch reminiscence (RAM) that it has allotted however is not utilizing.

Over time, if reminiscence leaks aren’t addressed, they will result in this system consuming increasingly reminiscence, finally inflicting it to decelerate and even crash as a consequence of working out of accessible reminiscence.

We will use profiling instruments in Android Studio and iOS Xcode to detect reminiscence leaks. These instruments assist determine areas the place reminiscence consumption is rising, though pinpointing the precise causes will be difficult. Detecting reminiscence leaks in an app will be troublesome, so it’s greatest to maintain the above factors in thoughts to forestall reminiscence leak points.

Once we register any timers, listeners, or subscriptions, it’s necessary to unregister them throughout element unmount. In any other case, these timers, listeners, or subscriptions will proceed to name occasions even when we’re not on these parts, resulting in elevated unused reminiscence.


useEffect(() => {
  const handleAppStateChange = (nextAppState: AppStateStatus) => {
    console.log("App state modified to:", nextAppState);
  AppState.addEventListener("change", handleAppStateChange);
  return () => {
    AppState.removeEventListener("change", handleAppStateChange);
}, []);

Resolution 2: Keep away from utilizing world variables unnecessarily

International variables persist so long as the app is working, as a result of they’re accessible from anyplace within the app’s scope. Because of this, the rubbish collector interprets them as nonetheless in use and doesn’t deallocate them.

Resolution 3: Round object references

Creating object references the place two objects are pointing to one another will forestall rubbish assortment, as a result of the rubbish collector assumes the objects are nonetheless in use.


const person1 = {
  title: "Alice",
  pal: person2,

const person2 = {
  title: "Bob",
  pal: person1,

Debugging itself is primarily centered on figuring out and resolving points inside an utility’s codebase moderately than straight enhancing efficiency. Nevertheless, by the method of debugging, builders might determine and tackle performance-related points equivalent to inefficient algorithms, extreme re-renders, or reminiscence leaks, which might in the end result in efficiency enhancements.

Debugging and efficiency monitoring are essential elements of growing React Native functions to make sure clean and environment friendly consumer experiences. Under, I’ll point out some instruments for debugging and efficiency monitoring.

1. Profiling instruments

Use profiling instruments offered by platforms like Android Studio Profiler for Android and Xcode Devices for iOS. These instruments provide insights into CPU utilization, reminiscence allocation, community requests, and different efficiency metrics. You’ll be able to observe the under steps to open the profiler in each Android Studio and Xcode.

Notice: figuring out reminiscence leaks will not be all the time easy, however these instruments might help analyze potential points within the code.

Android Studio

Open Android Studio > View > Instrument Home windows > Profiler.

The Profiler window will show CPU and Reminiscence utilization. Strive accessing totally different screens within the app and observe the Profiler window to determine which display screen makes use of excessive CPU and reminiscence assets. Then you possibly can test the code and logs to repair any points.


Open Xcode > Xcode menu > Developer Instrument > Devices.

As soon as Devices is chosen, a brand new popup window will seem, providing a number of choices equivalent to Exercise Monitor, CPU Profiler, Leaks, and so forth. If you wish to test for reminiscence leaks, click on on the Leaks choice. Right here you’ll discover an exercise graph together with logs.

2. Chrome’s DevTools

Chrome’s DevTools is a generally used device for debugging React Native functions. Though primarily designed for debugging internet apps, its JavaScript capabilities permit for debugging React Native functions as properly. It lets you examine community exercise, reminiscence utilization, and JavaScript efficiency.

To apply it to Home windows, press CTRL + M, and on macOS, press Command + R. Should you’re utilizing a Bodily gadget, then you possibly can shake the cellular gadget to open the window in your telephone.

Notice: for those who’re utilizing React Native 0.73 or later, you possibly can’t use it as a result of it’s deprecated.

If you wish to study extra about Chrome’s DevTools, try our browser DevTools secrets and techniques article.

3. React DevTools

React DevTools lets you examine the props and state of particular person parts in your React Native utility. By monitoring adjustments in props and state, you possibly can determine potential efficiency bottlenecks.

React DevTools gives insights into element re-renders, permitting you to determine parts which are re-rendering unnecessarily and optimizing them for higher efficiency.

Whereas React DevTools doesn’t provide built-in efficiency profiling particularly tailor-made for React Native, you possibly can nonetheless use it at the side of different profiling instruments like Chrome DevTools or Xcode Devices to observe efficiency metrics equivalent to rendering occasions, CPU utilization, and reminiscence allocation.

You’ll be able to run the npx react-devtools command to open React DevTools.

Yow will discover out much more about React DevTools right here.

4. Flipper

Flipper is a robust debugging device developed by Fb that helps React Native. It presents numerous plugins for inspecting community requests, database queries, and UI rendering efficiency.

The Format Inspector plugin in Flipper lets you visualize and examine the hierarchy of React Native parts.

5. React Native Efficiency Monitor

This can be a built-in efficiency monitoring device offered by React Native itself. It lets you monitor numerous efficiency metrics equivalent to FPS (frames per second), CPU utilization, reminiscence utilization, and community requests straight inside your app.

To apply it to Home windows, press CTRL + M, and on macOS, press Command + R. You’ll get the present per monitor choice.

If you wish to know extra, you possibly can go to the React Native Official web site.

Take away Console Logs

Console logs can decelerate app efficiency by printing logs to the console. Due to this fact, it’s advisable to keep away from utilizing console logs in manufacturing.

Resolution 1: Use _DEV_ world variable

Use the next code in a utility file and reuse it in all places. This code will execute console.log solely in improvement mode with the assistance of _DEV_, however keep away from it in manufacturing mode.


const logger ={
    log: __DEV__ ? console.log : ()=>{},
    error:__DEV__ ? console.error : ()=>{}
logger.log(“show values†,knowledge);

On this code snippet, logger.log and logger.error will respectively use console.log and console.error provided that _DEV_ evaluates to true, indicating that the appliance is working in improvement mode. In any other case, they are going to be set to empty features, guaranteeing that they haven’t any impact in manufacturing mode.

Use babel-plugin-transform-remove-console

The babel-plugin-transform-remove-console plugin removes console.log within the manufacturing construct. This leads to higher efficiency to your utility in manufacturing mode.

There are a lot of instruments obtainable within the React Native ecosystem for debugging and efficiency monitoring, together with Reactotron, Firebase Efficiency Monitoring, and extra. Explaining all these instruments intimately would make the article longer. Due to this fact, you possibly can deal with utilizing any one of many above instruments to determine and tackle points.


In conclusion, optimizing React Native app efficiency is essential for a seamless consumer expertise. By balancing animations, minimizing re-rendering, optimizing photos, and utilizing secure npm packages, builders can improve app velocity and responsiveness.

Moreover, leveraging environment friendly debugging instruments and eradicating pointless console logs additional improves efficiency.

Prioritizing these optimization strategies ensures peak efficiency and superior consumer satisfaction in at present’s aggressive app market.

Supply hyperlink

More articles


Please enter your comment!
Please enter your name here

Latest article