DEV Community

Cover image for React native Lazy component
Tuan Luong
Tuan Luong

Posted on

React native Lazy component

Cover Credit

Brief story

Recently, I worked on a screen that has multiple tabs, each tabs has multiple heavy components (charts, large lists, ...). And everything is imported to the main screen that make it very slow to load.

So, I came up with something like lazy loading. Just load the component when needed.

Before 🙁

import HeavyTab1 from './components/HeavyTab1'
import HeavyTab2 from './components/HeavyTab2'
import HeavyTab3 from './components/HeavyTab3'

export default function Screen() {
    const [currentTab, setCurrentTab] = useState('tab1')

    return (
        <View>
            {currentTab === 'tab1' && (
                <HeavyTab1 prop1={data1} props2={data2} />
            )}
            {currentTab === 'tab2' && <HeavyTab2 />}
            {currentTab === 'tab3' && <HeavyTab3 />}
        </View>
    )
}
Enter fullscreen mode Exit fullscreen mode

After 😍

import LazyComponent from "@r0b0t3d/react-native-lazy-component";

export default function Screen() {
    const [currentTab, setCurrentTab] = useState('tab1')

    return (
        <View>
            <LazyComponent
                visible={currentTab === 'tab1'}
                load={() => import('./components/HeavyTab1')} // or require('./components/HeavyTab1')
                prop1={data1}
                props2={data2}
            />
            <LazyComponent
                visible={currentTab === 'tab2'}
                load={() => import('./components/HeavyTab2')}
            />
            <LazyComponent
                visible={currentTab === 'tab3'}
                load={() => import('./components/HeavyTab3')}
            />
        </View>
    )
}
Enter fullscreen mode Exit fullscreen mode

Check it out @r0b0t3d/react-native-lazy-component

Happy coding!

Top comments (0)