Use React.lazy() to render components conditionally

You can use the React.lazy() function conditionally to ensure a component is rendered only if it is needed.

OSF makes extensive use of server-side rendering to speed up loading of pages. In some cases, however, a component will have code that should not be rendered in advance, such as a user interface element that is displayed conditionally. For example, a popup that is displayed when an item is added to the shopping cart should be rendered only when the shopper clicks the Add to Cart button.

In the following example, LazyComponent is rendered only if the shopper clicks the Show Component button:

const LazyComponent = React.lazy(() => import('./component));
 
const [showComponent, setShowComponent] = useState(false);
 
const ParentComponent = () => {
   return (
      <div>
        <button onClick={() => setShowComponent(!showComponent)}> Show Component
        </button>
        {showComponent && <LazyComponent />}
      </div>
     );
};

This approach can be used for CSS as well. Styles that apply only to the lazy-loaded component can be placed in the component-specific CSS file, so they will also be loaded only when needed.