Inline Requires: Defer JS Loading in React Native
Inline requires are just-in-time loading for code. Instead of loading everything at startup, you pull in modules only when needed, improving initial app speed. This is ideal for heavy components. The footgun: module side effects will execute later.
WHY IT EXISTS As a React Native app grows, its startup time can suffer. Parsing and executing all the app's JavaScript code upfront becomes a performance bottleneck. To keep the app responsive from launch, we need a way to load code only when it's actually needed.
THE MENTAL MODEL Think of an inline require as leaving a book on the shelf until you need to read a specific chapter. A standard import is like opening every book on your desk the moment you sit down. You trade the high upfront cost of loading everything for a small, deferred cost at the exact moment of use, improving initial app startup time.
HOW IT WORKS Normally, import statements at the top of a file are processed when the module is first loaded. An inline require, such as const MyModule = require('./MyModule');, is placed inside a function or callback. The JavaScript engine only executes this line—and thus loads and parses the module—when that function is called. The React Native CLI build process can even automatically convert top-level require calls (but not import statements) into this lazy-loaded behavior.
WHEN TO USE IT Use this advanced technique for large, expensive modules or components that are not needed for the initial screen render. It's an optimization for when React.lazy and Suspense are not a fit, or for when you need synchronous loading on-demand within a function. It is most effective in large apps with many screens or complex, isolated features.
WHEN NOT TO USE IT Avoid this for small, critical modules needed at startup. More importantly, do not use it for modules with side effects that other parts of your app expect to have run at launch. If a module modifies a global variable or subscribes to a system event, lazy-loading it can lead to race conditions or broken logic. For UI components, React.lazy is often a better, more declarative choice.
ONE CANONICAL EXAMPLE To defer loading a 'VeryExpensive' component until a button is pressed, you would not import it at the top. Instead, inside the button's press handler, you check if the component has been loaded. If not, you call VeryExpensive = require('./VeryExpensive').default and store it in a variable, then update state to trigger a re-render that displays it. This ensures the code for 'VeryExpensive' is not part of the initial JavaScript payload.
Read the original → reactnative.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.