Master lazy loading concept in React Native/ReactJS
Lazy Loading is a design pattern in which resources are loaded only when they are needed. This is beneficial for improving the initial load time of a React Native application, reducing memory consumption, and improving overall performance.
Why Lazy Loading?
- Performance Optimization: It prevents the loading of unnecessary resources during the app's initial launch, which can significantly reduce the load time.
- Reduced Memory Usage: Lazy loading prevents keeping large resources like images, components, or external libraries in memory when they are not needed.
- Improved User Experience: Loading resources on demand provides smoother navigation and interaction.
1) Use Cases of Lazy Loading in React Native screens/components
Lazy Loading Screens (Code Splitting):
In React Native, lazy loading is typically used for components, especially when you have different screens that the user might not visit frequently. By lazily loading these screens, you reduce the initial bundle size.Lazy Loading with React.lazy() and Suspense:
React introduced the React.lazy() function to enable lazy loading of components. To use lazy loading, Suspense is used as a fallback until the component loads.
Normal Usage
In normal usage, all resources, components, libraries, and data are loaded upfront when the app starts. This approach works fine for small applications but can become inefficient and resource-intensive as the app grows, affecting performance and load times.
Example: Normal Component Loading
import React from 'react'; import HomeScreen from './screens/HomeScreen'; import ProfileScreen from './screens/ProfileScreen'; const App = () => { return ( <> <HomeScreen /> <ProfileScreen /> </> ); }; export default App;
Explanation:
- In this example, both HomeScreen and ProfileScreen components are imported and loaded upfront, regardless of whether the user navigates to them or not.
- This increases the initial load time because all components are bundled and loaded at once.
Lazy Loading Usage
With lazy loading, components, libraries, or data are loaded only when needed. This improves performance by reducing the initial load time and memory usage since only the necessary resources are loaded on demand.
Example: Lazy Loading Components
import React, { Suspense, lazy } from 'react'; import { ActivityIndicator } from 'react-native'; const HomeScreen = lazy(() => import('./screens/HomeScreen')); const ProfileScreen = lazy(() => import('./screens/ProfileScreen')); const App = () => { return ( <Suspense fallback={<ActivityIndicator size="large" color="#0000ff" />}> <HomeScreen /> <ProfileScreen /> </Suspense> ); }; export default App;
Explanation:
- In this example, the HomeScreen and ProfileScreen are lazily loaded using React.lazy().
- Until these components are loaded, a fallback (ActivityIndicator) is shown.
- This reduces the app’s initial load time since components are only loaded when they are rendered.
Differences Between Normal and Lazy Loading
Feature | Normal Usage | Lazy Loading | |||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Everything is loaded upfront when the app starts. | Components, resources, or data are loaded only when needed. | |||||||||||||||||||||
Initial Load Time | Higher, as all resources are loaded at once. | Lower, as only essential components are loaded upfront. | |||||||||||||||||||||
Memory Usage | Higher, as all components and resources are loaded into memory. | Lower, as only necessary components are loaded into memory. | |||||||||||||||||||||
User Experience | Slower startup but smoother transitions once loaded. | Faster startup but slight delay when loading resources. | |||||||||||||||||||||
Best for | Small applications with limited components. | Large applications where not all components are used initially. | |||||||||||||||||||||
Implementation | Simpler, as everything is bundled at once. | Requires managing dynamic imports and possibly loading states. |
2. Lazy Loading in Navigation (React Navigation):
Lazy loading ensures that screens or components are only mounted when they are accessed (when the user navigates to them), thus improving performance, especially in apps with multiple screens.
Example: Lazy Loading in React Navigation (Stack Navigator)
import React, { Suspense, lazy } from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import { NavigationContainer } from '@react-navigation/native'; import { ActivityIndicator } from 'react-native'; // Lazy load screens const HomeScreen = lazy(() => import('./screens/HomeScreen')); const ProfileScreen = lazy(() => import('./screens/ProfileScreen')); const Stack = createStackNavigator(); const App = () => { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Home" component={() => ( <Suspense fallback={<ActivityIndicator size="large" color="#0000ff" />}> <HomeScreen /> </Suspense> )} /> <Stack.Screen name="Profile" component={() => ( <Suspense fallback={<ActivityIndicator size="large" color="#0000ff" />}> <ProfileScreen /> </Suspense> )} /> </Stack.Navigator> </NavigationContainer> ); }; export default App;
Explanation:
- In this example, the HomeScreen and ProfileScreen components are lazily loaded using React.lazy().
- The Suspense component provides a loading indicator (ActivityIndicator) while the components are being loaded.
- Screens will only load when the user navigates to them, reducing the initial load time.
3. Lazy Loading Images :
In React Native, lazy loading can be achieved using libraries like react-native-fast-image or manually handling image loading by tracking visibility with tools like IntersectionObserver.
a) Using react-native-fast-image
react-native-fast-image is a performant image component that provides built-in lazy loading.
npm install react-native-fast-image
Example: Lazy Loading Images with react-native-fast-image
import React from 'react'; import { View, ScrollView, Text } from 'react-native'; import FastImage from 'react-native-fast-image'; const LazyLoadingImages = () => { return ( <ScrollView> <Text>Scroll down to load images</Text> <FastImage style={{ width: 200, height: 200 }} source={{ uri: 'https://example.com/my-image1.jpg', priority: FastImage.priority.normal, }} resizeMode={FastImage.resizeMode.contain} /> <FastImage style={{ width: 200, height: 200 }} source={{ uri: 'https://example.com/my-image2.jpg', priority: FastImage.priority.normal, }} resizeMode={FastImage.resizeMode.contain} /> </ScrollView> ); }; export default LazyLoadingImages;
Explanation:
- The FastImage component from react-native-fast-image helps with lazy loading. It loads images only when they are about to be displayed.
- It also provides efficient caching and priority options, improving performance.
b) Manual Lazy Loading (Visibility Tracking)
In cases where you don't want to use a third-party library, you can implement lazy loading by tracking when an image enters the viewport using tools like IntersectionObserver (web) or a custom scroll listener in React Native.
Example: Lazy Loading with Visibility Tracking (using React Native)
import React, { useState, useEffect } from 'react'; import { View, Image, ScrollView } from 'react-native'; const LazyImage = ({ src, style }) => { const [isVisible, setIsVisible] = useState(false); const onScroll = (event) => { // Implement logic to determine if image is visible based on scroll position const { y } = event.nativeEvent.contentOffset; if (y > 100) { // Example: load image when scrolled past 100px setIsVisible(true); } }; return ( <ScrollView onScroll={onScroll} scrollEventThrottle={16}> <View> {isVisible ? ( <Image source={{ uri: src }} style={style} /> ) : ( <View style={style} /> )} </View> </ScrollView> ); }; const App = () => { return ( <LazyImage src="https://example.com/my-image.jpg" style={{ width: 200, height: 200 }} /> ); }; export default App;
Explanation:
- The LazyImage component only loads the image once the user has scrolled a certain amount (onScroll event).
- This approach manually tracks the scroll position and loads the image accordingly.
4. Lazy Loading with Redux (Dynamic Reducers) :
When using Redux, you may want to lazy load certain reducers only when necessary, such as for specific screens or features.
- Create a function to inject reducers dynamically.
- Add the new reducer to the Redux store when needed (e.g., when a user navigates to a new screen).
- Remove the reducer when it is no longer needed (optional).
Example: Lazy Loading Reducers in a React Application with Redux
1. Initial Redux Store Setup
Start by setting up a standard Redux store, but instead of adding all reducers upfront, create an injection method.
import { configureStore, combineReducers } from '@reduxjs/toolkit'; const staticReducers = { // Add reducers that are needed from the start }; export const createReducer = (asyncReducers = {}) => { return combineReducers({ ...staticReducers, ...asyncReducers, }); }; const store = configureStore({ reducer: createReducer(), }); // Store injected reducers here store.asyncReducers = {}; export default store;
In the above code:
- staticReducers: Contains reducers that are loaded when the app starts.
- asyncReducers: This object will contain dynamically injected reducers as they are loaded.
2. Dynamic Reducer Injection Method
Create a helper function to inject new reducers dynamically into the store.
// Helper function to inject a new reducer dynamically export function injectReducer(key, asyncReducer) { if (!store.asyncReducers[key]) { store.asyncReducers[key] = asyncReducer; store.replaceReducer(createReducer(store.asyncReducers)); } }
The injectReducer function checks if a reducer has already been added. If not, it injects it into the store and replaces the current root reducer.
3. Loading Reducer When Needed (Lazy Loading)
Imagine you have a new page or feature that needs its own reducer. You can inject the reducer dynamically when this page is loaded.
import { lazy, Suspense, useEffect } from 'react'; import { useDispatch } from 'react-redux'; import { injectReducer } from './store'; import featureReducer from './features/featureSlice'; // The reducer for this feature const FeatureComponent = lazy(() => import('./components/FeatureComponent')); const FeaturePage = () => { const dispatch = useDispatch(); useEffect(() => { injectReducer('feature', featureReducer); // Dynamically load the reducer }, [dispatch]); return ( <Suspense fallback={<div>Loading...</div>}> <FeatureComponent /> </Suspense> ); }; export default FeaturePage;
Here:
- When the FeaturePage component is loaded, the injectReducer function adds the featureReducer dynamically to the Redux store.
- The Suspense component handles lazy loading of the FeatureComponent.
4. Feature Reducer Example
The reducer for the feature is written as usual, using Redux Toolkit.
import { createSlice } from '@reduxjs/toolkit'; const featureSlice = createSlice({ name: 'feature', initialState: { data: [] }, reducers: { setData: (state, action) => { state.data = action.payload; }, }, }); export const { setData } = featureSlice.actions; export default featureSlice.reducer;
Removing a Reducer (Optional)
You might want to remove a reducer when it's no longer needed, for example, when navigating away from a page.
Here’s how you can remove a reducer:
export function removeReducer(key) { if (store.asyncReducers[key]) { delete store.asyncReducers[key]; store.replaceReducer(createReducer(store.asyncReducers)); } }
You can call this function when a feature or page is unmounted to remove its reducer from the store.
5. Lazy Loading Libraries/Packages:
If you are using heavy third-party libraries, lazy loading them can help optimize performance.
import React, { useState } from 'react'; const HeavyComponent = React.lazy(() => import('heavy-library')); // React.lazy(() => import('moment')) const App = () => { const [showComponent, setShowComponent] = useState(false); return ( <View> <Button title="Load Heavy Component" onPress={() => setShowComponent(true)} /> {showComponent && ( <Suspense fallback={<Text>Loading...</Text>}> <HeavyComponent /> </Suspense> )} </View> ); };
- Lazy Loading Data: You can also implement lazy loading for data fetching, where data is fetched in chunks or when a user scrolls (infinite scroll).
Example: Lazy Loading Data:
import React, { useState, useEffect } from 'react'; import { FlatList, ActivityIndicator, Text } from 'react-native'; const LazyLoadData = () => { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(json => { setData(json); setLoading(false); }); }, []); if (loading) { return <ActivityIndicator />; } return ( <FlatList data={data} renderItem={({ item }) => <Text>{item.name}</Text>} keyExtractor={item => item.id} /> ); }; export default LazyLoadData;
Explanation:
- Fetching data lazily ensures that the app doesn’t load too much data at once, improving performance and reducing bandwidth usage.
Summary of Use Cases:
- Screens/Components: Lazy loading React Native screens or components using React.lazy() and Suspense.
- Images: Lazy loading images as they enter the viewport to save memory and bandwidth.
- Redux Reducers: Injecting reducers dynamically to reduce the initial store size in Redux.
- Libraries: Lazily load third-party libraries or packages to reduce the initial bundle size.
- Data: Implement lazy loading for large datasets using techniques like pagination or infinite scrolling.
Lazy loading helps improve the performance, memory usage, and user experience of your React Native app, making it more efficient and responsive for users.
The above is the detailed content of Master lazy loading concept in React Native/ReactJS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
