Morado labs

Why order your imports in React.js?

June 23, 2023

Ever opened up a React.js component file and the first thing you see are imports that look like this:

(Note this example is using Next.js)

 

 

I know I have. Immediately I wonder what is going on and what is actually used in the component.

React.js applications provide us with a lot of benefits. We get a lot of flexibility with how we structure our applications. This can lead us to having components, helpers and hooks located all over our app.

When we add no structure to our imports, it can leave developers scratching their head when they open up a new component.

One simple solution to this problem is to have a structured order to our imports. This allows ourselves and other developers to easily scan a file and see which imports are used.

 

Determine the type of each import

We can break down which imports are what in the above snipped like the Following (see comment beside each import):

 

 

Ordering the imports

Now that we have broken them down – we can use the list below to order our imports by direct relevance to the component.

  • React imports (Hooks)
  • Framework Specific Imports (Gatsby Image, Next Link )
  • NPM Package Imports
  • Custom Hooks
  • Context
  • Global Helpers
  • UI Components
  • Services (API request logic)
  • Components
  • SVG Components
  • Local Helpers/Schemas

Using this list, we can re-order our imports:

 

 

I usually add a line so that we can easily distinguish the separation of different types of inputs.

You can even go a step further by order imports of the same category alphabetically.

 

Summary

By keeping this pattern across an app, each developer can reduce their mental overload from reading unreadable code. This allows us to save that space for solving the hard problems.

Share

Facebook
Twitter
LinkedIn
WhatsApp

Other articles

What is React.js

React.js is a JavaScript based library used to build user-interfaces (UI’s) on the web. It provides functionality that allows software developers to build interactive and

Read more »