How to implement RAM bundle and Inline Requires react native

Viewed 1926

I am using react native to build project and I am facing a problem with long launch time, I try to follow https://reactnative.dev/docs/ram-bundles-inline-requires, however it is not so clear about Investigating the Loaded Modules, and how to put only the necessary modules for first screen. I am not also able to find index.(ios|android).js file (is it index.android.bundle). If you can tell me how to extract only necessary modules and recommend docs or examples about implementing that?

1 Answers

With considering the official documents, pay attention to this example:

You have a Main screen (view) in your app like HomeScreen

In your HomeScreen, there are more and more components and logic in this page but assume we have a SettingsModal.

usually, modals will open when you touch a button.

Without inline require

you have to import your modal component to your HomeScreen at the top level of your module

with inline require

you will import your modal component to your HomeScreen when it needs to show!

Let's do this with code:

HomeScreen without inline require

import React, {useState} from 'react'
import {View, Text, Pressable} from 'react-native'
import SettingsModal from 'components/modal'

function HomeScreen() {
    const [showModal, setShowModal] = useState(false)

    const handleShowModal = () => setShowModal(prevState => !prevState)
   
    return (
       <View>
          <Text> Home Screen </Text>

          <Pressable onPress={handleShowModal}>
              <Text> show settings </Text>             
          </Pressable >

          {
            showModal 
                ?  <SettingsModal />
                :  null
          }
       </View>
    )
}

In the above example, we import SettingsModal in our HomeScreen top level with React and View and Text...

HomeScreen with inline require

import React, {useState} from 'react'
import {View, Text, Pressable} from 'react-native'

let SettingsModal = null;

function HomeScreen() {
    const [showModal, setShowModal] = useState(false)

    const handleShowModal = prevState => {
         if (SettingsModal == null) {
             SettingsModal = require('components/modal').SettingsModal
         }
         
         setShowModal(prevState => !prevState)
    }
   
    return (
       <View>
          <Text> Home Screen </Text>

          <Pressable onPress={handleShowModal}>
              <Text> show settings </Text>             
          </Pressable >

          {
            showModal 
                ?  <SettingsModal />
                :  null
          }
       </View>
    )
}

In the above example, we check if SettingsModal has not been imported yet, then we will import this component to our HomeScreen file (after user touch the show settings button)

Related