DEV Community

Cover image for How I Structure my React Projects
phukon
phukon

Posted on

How I Structure my React Projects

Ever dreamt of a React app that chuckles at bugs and scoffs at spaghetti code? Let’s embark on a journey to create a React app so robust it could survive an apocalypse of bad coding practices.

In those novice days, my code resembled a wild creature — functional, yet utterly chaotic. The project structure, if you could call it that, was a disorganized mess. It sufficed for my humble beginnings, but as the project grew, so did the complexity, and chaos ensued.

Inexperienced dev ⤵
Image description

Experienced dev ⤵

Image description

With each expansion of the project, finding a specific piece of code became a quest akin to searching for a needle in a haystack, only to realize that the needle was a variable aptly named ‘needle’ buried somewhere deep in the code.

Take the time to learn how to structure your React project before your codebase transforms into an unsolvable mystery novel.

How a project should look like:

src
|
+-- assets            
|
+-- components        
|
+-- config           
|
+-- features          
|
+-- hooks             
|
+-- lib               
|
+-- providers         
|
+-- routes            
|
+-- stores            
|
+-- test              
|
+-- types             
|
+-- utils            
Enter fullscreen mode Exit fullscreen mode

components: Shared components that grace the entire kingdom
config: The vault of global configurations, env variables, and secrets
features: Feature based modules
hooks: Mystical hooks, shared across the entire realm
libs: re-exporting different libraries preconfigured for the application
providers: Keepers of the application’s life force, the providers
routes: routes configuration
stores: global state stores
test: The arena of trials, where utilities and mock servers prove their mettle
types: base types used across the application
utils: shared utility functions


Now, let’s descend into the heart of a feature.

src/features/my-new-feature
|
+-- api         # Declarations and API hooks, a symphony of requests for this feature
|
+-- assets      # Treasures specific to the awesome feature
|
+-- components  # Components, artisans sculpting the visual identity of the feature
|
+-- hooks       # Hooks, magical spells woven into the fabric of this feature
|
+-- routes      # Paths leading to the feature's pages, a roadmap of wonder
|
+-- stores      # Keepers of state, guarding the feature's sacred truths
|
+-- types       # TypeScript types, a lexicon for the feature's domain
|
+-- utils       # The craftsmen, building utility functions exclusive to this feature
|
+-- index.ts    # The grand entrance, the public API of this feature, revealing its essence
Enter fullscreen mode Exit fullscreen mode

The index file

Everything from a feature should be exported from the index.ts file which behaves as the public API of the feature.

Image description Notice the index file for each component folder. ⤴

You should import stuff from other features only by using:

import {AwesomeComponent} from "@/features/awesome-feature"

and not

import {AwesomeComponent} from "@/features/awesome-feature/components/AwesomeComponent

Set up absolute imports!

Absolute imports can make your import statements cleaner and more readable. They also help in avoiding long relative import paths.

//  jsconfig.json/tsconfig.json
"compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  }
Enter fullscreen mode Exit fullscreen mode

Remember, every developer, seasoned or fledgling, has danced the maddening tango with spaghetti code. But with structure comes clarity, and with clarity comes the power to wield React with finesse.

So, as you forge your own path in the realms of frontend development, let this blueprint be your guiding light, your treasure map to organized brilliance. May your React projects chuckle at bugs, scoff at chaos, and stand firm in the face of coding calamities.


Personal links.:
web
GitHub

Footnotes:
https://github.com/alan2207/bulletproof-react

Top comments (9)

Collapse
 
shezan profile image
J.A. Shezan • Edited

You have provided a nice Project Structure.

Bash Command to create your proposed File Structure (Run this inside the parent folder of src folder):

mkdir -p src/{assets,components,config,features,hooks,lib,providers,routes,stores,test,types,utils} && find src/assets src/components src/config src/features src/hooks src/lib src/providers src/routes src/stores src/test src/types src/utils -type d -exec bash -c 'test -e "{}/index.ts" || echo > "{}/index.ts"' \;

Enter fullscreen mode Exit fullscreen mode

Here the command will first check if the folder already exists or not.
If the directory does not exists then it will create one, then check for existing index.ts and will create a index.ts if not available.

This does not include structure for nested features structure, but you can easily derive one from my command.

Collapse
 
phukon profile image
phukon

thank you so much man!

Collapse
 
webdev-mohdamir profile image
Mohd Amir

I am just a beginner at react but by following the hit and trial method I did follow the same structure as you discussed in this article.(Second Last index.ts was good suggestion). I Love the article tho.

Collapse
 
lakincoder profile image
Lakin Mohapatra

Nice article

Collapse
 
21blackjac profile image
Mustapha

Nice post!!!

Collapse
 
aimeetacchi profile image
Aimee

Nice post!!!

Collapse
 
imloadinqqq profile image
Alex Diaz

This is an awesome read, thank you!

Collapse
 
vorant94 profile image
Mordechai Dror • Edited

barrel exports hurt bundler performance, you should probably avoid them unless you write back-end js. but then you also should probably use ES modules, which are a little bit less pretty (you have to import from /feature-a/index.js instead of just /feature-a

vitejs.dev/guide/performance#avoid...

Collapse
 
yeasin2002 profile image
Md Kawsar Islam Yeasin

After reading the blog, I feel that I have become a senior developer because I always follow this kind of thing.
Even I have a starter template that follow these things

Link : github.com/yeasin-2002/react-ts-st...