'React Tabs Lazy Load

I am a React beginner from jquery. Let's say I have three tabs. I am looking for a way to lazy-load the 3 tab-contents so that when I click Tab1 the first time, only the tab1 contents will be loaded and stay in the DOM (not the tab2 and tab3 contents). When I click Tab2, the tab2 contents will then be loaded (not the tab3 contents). When I click Tab1 again, the original tab1 content will stay there in the DOM without reloading and re-rendering.

This is the code:

<div className="tab-content">
  {/* Tab1 */}
  <div hidden={tab1.name !== activeTab ? true : false}>
    <tab1.component />
  </div>
  {/* Tab2 */}
  <div hidden={tab2.name !== activeTab ? true : false}>
    <tab2.component />
  </div>
  {/* Tab3 */}
  <div hidden={tab3.name !== activeTab ? true : false}>
    <tab3.component />
  </div>
</div>

It works, but the problem is that all the three components (tab1.component, tab2.component & tab3.component) got loaded at the same time, even the user never clicks tab2 or tab3, causing wasted processing in the server.

Both the contents in tab2 and tab3 require 'expensive' processing at the server, that's why I want to avoid that.

Thank you.



Solution 1:[1]

You can have a wrapping component like this:

type LazyProps = {
    visible: boolean;
}

function Lazy({visible, children}: PropsWithChildren<LazyProps>) {
    const rendered = useRef(visible);

    if (visible && !rendered.current) {
        rendered.current = true;
    }

    if (!rendered.current)
        return null;

    return <div style={{display: visible ? 'block' : 'none'}}>{children}</div>;
}

And use it like this:

<div className="tab-content">
    <Lazy visible={tab1.name === activeTab}><tab1.component /></Lazy>
    <Lazy visible={tab2.name === activeTab}><tab2.component /></Lazy>
    <Lazy visible={tab3.name === activeTab}><tab3.component /></Lazy>
</div>

The idea is to avoid rendering the tab content until visible prop becomes true the first time. After that visible prop only affects the display css rule and therefore state of the tabs is kept.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexander Kravets