(Jump to Code | Demo) One of the most important feature of Reactjs is its modularity. To make code more readable and maintainable, we break it into reusable components.

And most of the times we need to dynamically add these components into scripts.

First of all let’s understand the difference between static component and dynamic component. Static components are included at the compile time while dynamic components are included at run time.

Syntax to add dynamic component

const DynamicComponent = React.lazy(() => import('./DynamicComponent'));

You may use other techniques to create a component at run time. React has createElement function which can be used to create elements as well as complete components. But this approach is messy and hard to maintain. The best way is to create component using JSX and lazy load it when required.

Code Example to dynamically add component

In this example we will create two components –

  1. DynamicComponent – We will render this lazily. The content is the list of famous dialogues of Chandler Bing of friends.
  2. App – This is the landing page where we are going to dynamically add our component.

First, let’s code our DynamicComponent

import React from "react";

export default function DynamicComponent() {
  const dialogues = [

  return dialogues.map((element, index) => {
    return (
        style={{ marginBottom: 20, border: "1px solid #000", padding: 5 }}
        <img src={element} style={{ width: "100%", maxWidth: "400px" }} />

This component will display a list of memes of world famous Chandler Bing. We created an array to store all the image urls. In return function, we are running a loop over this array and displaying images.

Now check out the code of our landing page (App) and how we are dynamically adding our component –

import React, { Suspense } from "react";
const DynamicComponent = React.lazy(() => import("./DynamicComponent"));

export default function App() {
  const [loadDynamicComp, setLoadDynamicComp] = React.useState(0);

  return (
      <p>Click button to load dynamic component</p>
      <button onClick={() => setLoadDynamicComp(1)}>
        Load Dynamic Component
      {loadDynamicComp ? (
        <Suspense fallback={<div>Loading Component....</div>}>
          <DynamicComponent />
      ) : null}

You can see that adding a dynamic component is a two way process. First we import it using React.lazy(). Then we wrap it in a wrapper component, Suspense. It has one prop, fallback, which renders anything inside it till DynamicComponent is loading.