Dhananjay Kuber

Performance Upgradation for ReactJS

Performance optimization is crucial in ReactJS for several reasons, as it directly impacts the user experience, the responsiveness of the application, and how efficiently resources are utilized. There are many ways to improve the performance of React application. One one the widely used performance optimization technique is the way we import components in React.

Following are two ways of imports

  1. Static Import
  2. Dynamic Import

Static Import

  • Static imports are used to brining different utilitues, components from different file or third party packages at the begining of the file.
// App.tsx
import EmojiPicker from 'emoji-picker-react';

const App = () => {
  return (
    <div>
      <h5>Static imports</h5>
      <EmojiPicker />
    </div>
  );
};

export default App;
  • In above example the EmojiPicker is statistically imported on the top and used in App component

Dynamic Import

  • Dynamic imports provide a mechanism for loading utilities, modules, and components asynchronously during runtime.
  • In React dynamic imports are commonly used for lazy loading components.
  • import() function is used to dynamically import the modules
  • This strategy is particularly beneficial for scenarios where certain parts of the application are not immediately required on the initial page load.
// App.tsx;
import { lazy, Suspense } from 'react';

const EmojiPicker = lazy(() => import('emoji-picker-react'));

const App = () => {
  return (
    <div>
      <h5>Dynamic imports</h5>
      <Suspense fallback={<p>Loading Emoji Picker</p>}>
        <EmojiPicker />
      </Suspense>
    </div>
  );
};

export default App;
  • Here we are using lazy function and dynamic import to asynchronously load the emoji-picker-react component.
  • Suspense component is used to display the fallback UI

Before EmojiPicker component loads

Dynamic Import before EmojiPicker loads

After EmojiPicker component loads

Dynamic Import after EmojiPicker loads