DEV Community

Cover image for 1 Next.js Import to Rule Them All in Performance
Muhammad Zakiullah Usman
Muhammad Zakiullah Usman

Posted on • Edited on

1 Next.js Import to Rule Them All in Performance

I recently read an article that got me interested in optimizing performance in React web applications.

The article discussed how we can use Dynamic Imports, Lazy and Suspense for code-splitting.

Since I am currently working on a project in Next.js, but I still wanted to implement what I learned as quickly as possible, I looked for how to do the same in Next.js.

It turned out that its actually much more straightforward in Next.

In Next.js, you don't need to use React.lazy and Suspense for code splitting, as Next.js handles it automatically through its dynamic imports system.

So here is the code snippet shamelessly copied directly from the React article:

import React, { Lazy, Suspense } from 'react';

const MyComponent = Lazy(() => import('./MyComponent'));

const App = () => {
   return (
      <div>
         <h1>My React App</h1>
         <Suspense fallback={<div>Loading...</div>}>
            <MyComponent />
         </Suspense>
      </div>
   );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

And here's the same in Next:

import dynamic from 'next/dynamic';

const MyComponent = dynamic(
  () => import('./MyComponent'),
  { loading: () => <p>Loading...</p> }
);

const App = () => {
  return (
    <div>
      <h1>My Next.js App</h1>
      <MyComponent />
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Now all that's left is to see how it actually holds up when the e-commerce web application I am working on, going into production!

I'm sure there are loads(pun intended) of ways how to bring down your site's loading times. But I can only take the burden of learning one way at a time, and this has helped me, maybe this approach can work out for you.

As a fairly new MERN stack developer, I never really had to optimize for performance per say. But I still want to make my applications snappy. The quest for self-improvement goes on!

And there is a long, long way to go.

Let me know what other methods would you suggest I should learn both for Next and React web applications.

Happy coding!

Top comments (1)

Collapse
 
zia243 profile image
Ziamalik

I will also try in my Next js App