Parsing and running JavaScript costs memory and time, so as an app grows it pays to delay loading code until the moment it is first needed. React's lazy does this for components and an inline require() does it for any module. Either one can change how your app behaves when the module you defer does work of its own as it loads.
Key terms
- lazy: React's API for deferring the loading of a component's code until that component renders for the first time.
- Side effect: work a module does when it is evaluated beyond defining its exports, such as modifying a global variable or subscribing to events outside a component.
- Inline require: a
require()call placed where a value is first used, instead of a staticimportat the top of the file.
Screen components as the unit
lazy fits a component with a lot of code or dependencies that is unlikely to render when the app first opens. Screen-level components are the usual candidates. When each screen is lazy-loaded, adding a new screen to the app does not add to its startup time.
Modules that act when they load
Deferring a module changes when its top-level code runs. If a component module, or one of its dependencies, has side effects, lazy-loading it can change how your app behaves. Most modules in a React app should have none.
Take a ReportsScreen.tsx that sets up a money formatter for the whole app at module scope:
global.formatMoney = createMoneyFormatter('EUR');
That line runs when the module is evaluated, before React can begin to render ReportsScreen. While the screen is imported statically, the line runs at launch and every other screen can call global.formatMoney. Make ReportsScreen lazy and the line runs only when the screen first renders, so a call from another screen before that point finds undefined. Putting the formatter in its own module that exports it, and importing it wherever it is called, removes the side effect and leaves ReportsScreen safe to defer.
Requiring at the point of use
Sometimes you want to defer code without lazy or an asynchronous import(). Call require() at the point of use, where you would otherwise write a static import at the top of the file. The ExpenseForm example defers a large ReceiptScanner component until the user asks for it.
At module scope, where the static import would normally sit, ExpenseForm declares let ReceiptScanner: ComponentType | null = null;, so loading ExpenseForm evaluates nothing from ./ReceiptScanner. The press handler does the loading:
tsxif (ReceiptScanner == null) { ReceiptScanner = require('./ReceiptScanner').default; }
The .default reads the component's default export. Because of the == null check, the module is evaluated on the first press only, and later presses skip the require call. Finally the handler calls setShowScanner(true), and the JSX renders <ReceiptScanner /> only once that flag is true.
showScanner starts as false, so the first render shows the button and no scanner. The first press evaluates the ReceiptScanner module, then sets the flag, and the re-render that follows is the first one to render the scanner. The ReceiptScanner module is not evaluated at launch, and the user pays for evaluating it once, at the moment they ask for it.
The same side effect rule applies here. A deferred module whose top-level code patches a global or subscribes to events now does that work on the first press instead of at launch, so anything that depended on it running early can break in the same way the ReportsScreen formatter did.
Code Examples
import {useCallback, useState, type ComponentType} from 'react';
import {Pressable, Text, View} from 'react-native';
// A static import would evaluate ReceiptScanner as soon as this file loads:
// import ReceiptScanner from './ReceiptScanner';
let ReceiptScanner: ComponentType | null = null;
export default function ExpenseForm() {
const [showScanner, setShowScanner] = useState(false);
const openScanner = useCallback(() => {
if (ReceiptScanner == null) {
// Evaluated on the first press only
ReceiptScanner = require('./ReceiptScanner').default;
}
setShowScanner(true);
}, []);
return (
<View>
<Pressable onPress={openScanner}>
<Text>Scan a receipt</Text>
</Pressable>
{showScanner && ReceiptScanner != null ? <ReceiptScanner /> : null}
</View>
);
}