Search code examples
reactjslazy-loadingreact-functional-component

React lazy load for a function, not a component


I am working on a React v16 app and need to load a heavy (IMO) library for xlsx export of data.

I'm using functional components/hooks.

I understand and have used the <Suspense /> component and lazy for lazy loading modules. but since this item is not a component, it is simply a library function i need to run with an onClick event, i can't use lazy/suspense.

How can i lazy load this function only when needed? (writeXlsxFile)

import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
//...
import writeXlsxFile from "write-excel-file";

//...
  const fileCreate = async () => {
    await writeXlsxFile(exportData, {
      schema,
      fileName: `file.xlsx`,
    });
  };

return(//...

Solution

  • JavaScript, and by direct association, React, supports Dynamic Imports.

    So,

    const fileCreate = async () => { 
      const {default: writeXlsxFile} = await import ('write-excel-file')
      void await writeXlsxFile(exportData, {
          schema,
          fileName: `file.xlsx`,
      });
    }