Better file structure in React projects

victorocna

Victor Ocnarescu

Posted on August 20, 2021

Better file structure in React projects

Is there a perfect file structure for React projects? Probably not. But some are far better than others.

Over the years I discovered that I tend to structure files in some specific ways, which I believe are easier to understand and reasonable.

Meaningful folder names

Naming things is one of the toughest things to get right in programming. One of my favorite tactics to naming folders is to extract the subject and use it:

  • want a place for public resources? the public folder should be a good fit;
  • have some custom hooks that you are proud of? keep them easy to find in the hooks folder;
  • want to include yet another css file? store them in the css folder.

And so on and so forth.

Little to no folder nesting

I always wondered about the src folder and why it exists. And to this day it still is one of the many mysteries of programming.

I like to keep all my folders as close to the project root as possible. This way, they can be discovered more easily by any new dev working on the project.

Avoiding too much nesting is also recommended by the official React documentation as well.

Grouping by feature

The components folder is one of my exceptions: it has two (2) levels of nesting. Common components are accessible right from the folder root, while "specialized" components have they own folder.

The contents of the components folder:

  • Button.jsx - common button components
  • Link.jsx - common link component
  • Forms
    • AddClientForm.jsx - specific "form" component
    • EditClientForm.jsx - another specific "form" component

Minimal example

This is the project structure for a starter project I authored and for many projects I'm working on right now.

  • api
  • components
  • css
  • data
  • functions
  • hooks
  • models
  • pages
  • public
  • LICENSE
  • README.md

I hope the folder structure is self explanatory. If it is not, I have done a lousy job at naming folders. Let me know in the comment section below.

Closing thoughts

My favorite file structure:

  • is easy to read and understand
  • is shallow nested
  • is grouped by features

Have a different opinion? Can't wait to hear it!

đź’– đź’Ş đź™… đźš©
victorocna
Victor Ocnarescu

Posted on August 20, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related