Home > Software engineering >  React lazy load for a function, not a component
React lazy load for a function, not a component

Time:11-11

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(//...

CodePudding user response:

JavaScript (and by correlation, React) supports Dynamic Imports.

In any case, you can lazy load your functions by using the following piece of code:

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

-- Update 2021-11-10

This post explains that when using default imports. You have to invoke the default function in modules.

So,

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