Tutorials  /  JavaScript

Dynamically loading React components with hooks

Ccentron Redaktion · November 2023 ·4 min read ·JavaScript, Tutorial

Dynamic component loading and on-demand component loading can help improve maintenance and performance. We provide an overview of these techniques.

Dynamic Component Loading

Dynamic component loading is a technique that can replace writing import statements for many components. Instead of declaring every possible component that can be used, you can use a dynamic value for the path of a component. You can also use lazy loading to provide the end user with exactly the code bundle they need. A smaller bundle size for the end user should result in performance improvements. React 16.6.0+ provides React.lazy and React.Suspense to support lazy loading of React components. Instead of importing all components, lazy loading allows you to import only additional components when they are needed. In this article, you will explore the concepts of dynamic component loading and on-demand component loading.

Prerequisites

To complete this tutorial, you will need:

  • An understanding of JavaScript variables and functions. You can read the "How To Code in JavaScript" series for more in-depth knowledge.
  • An understanding of importing, exporting, and rendering React components. You can read our "How To Code in React.js" series for more in-depth coverage. No local development is required. CodeSandbox examples are available for further experimentation.
VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

Dynamic Component Loading

Suppose you are developing an application that displays views for three subreddits: r/reactjs, r/learnreactjs, and r/javascript. Depending on the subredditsToShow property, a different component is displayed. Here is an example of such an application:

JavaScript
import React from 'react';
import shortid from 'shortid';

import LearnReactView from './views/learnreactView';
import ReactView from './views/reactView';
import JavaScriptView from './views/javascriptView';
import NullView from './views/NullView';

export default function App({ subredditsToShow }) {
  // Code to display subreddit views
}

In this approach, you use a switch/case statement to determine which view is displayed. This works well for a handful of subreddits, but with additional subreddits, the code becomes cluttered. You can avoid this problem by loading components dynamically per subreddit and removing the switch statement. Here is a sample implementation:

JavaScript
import React, { lazy, useEffect, useState } from 'react';
import shortid from 'shortid';

const importView = subreddit =>
  lazy(() =>
    import(`./views/${subreddit}View`).catch(() =>
      import(`./views/NullView`)
    )
  );

export default function App({ subredditsToShow }) {
  // Code for dynamic component loading
}

In this implementation, views are dynamically loaded and stored in a state to be rendered later. This results in more efficient and maintainable code. You can also add a loading indicator to load the views.

Loading Components on Demand

In the previous examples, you loaded components automatically without any performance improvement. You can improve performance by sending JavaScript only when it is needed, when a user performs an action. Suppose you need to display different types of charts for the following data:

JavaScript
const data = [
  {
    id: 'php',
    label: 'php',
    value: 372,
    color: 'hsl(233, 70%, 50%)'
  },
  // More data records...
];

You can make the site load faster by avoiding unused JavaScript and loading charts only when they are needed. Here is a sample implementation:

JavaScript
import React, { lazy, useState } from 'react';
import shortid from 'shortid';

const importView = chartName =>
  lazy(() =>
    import(`./charts/${chartName}`)
      .catch(() => import(`./charts/NullChart`))
  );

const data = [ ... ];

export default function App() {
  // Code for loading components on demand
}

In this implementation, chart components are loaded only when the user clicks the corresponding buttons. This results in efficient use of resources and faster page execution. Dynamically Loading React Components with Hooks

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren