Today I will tell you about scalable folder structure in react application which helps me for more than 1.5 years to maintain a large react applications with more than 50k lines & 800+ files.
Abstraction:
First, we need to think about what do we use in our app, for example in my case I use assets, components, hooks, configs, router, pages, store, and types.
Simple questions to imagine our abstract structure:
- What are Assets for you? // Images, Icons, Etc
- Components? // Reusable/shared, grouped
- Configs? // Dynamic, constants
- Hooks? // Reusable/shared, grouped
- Router? // Navigation tree
- Pages? // Home, Custom, Sub
- Store? // Features, Initialization
- Types? // Reusable/shared, grouped
After it, we can try to realize them in a basic CRA(create react app) template.
Basic realization:
First, we need to install create-react-app with typescript template, I’m using yarn as package manager but you can install it with npx.
yarn create react-app react-folder-structure --template typescript
Structure after installation:
Here we don’t need index.css because we can use App.css as a global CSS file, logo.svg because we won’t use it.
After smaller cleanup we can create basic folders:
Then create abstract subfolders and index/styles files (I’m using SCSS modules, but if you want you can choose anything else).
Components folder for shared and grouped components:
Here you can see that for every group we create its folder like “home” and then we use the group names in our component names like “HomeFooter”.
Configs with dynamic in index.ts and constants in another folder:
Hooks folder for shared/grouped hooks:
Pages folder:
Router folder:
Store folder:
Types folder:
At the end our folder structure will look like this:
What are the benefits of such a structure?
- All components/hooks/types are ordered by page name (example: Home/home).
- We don’t need to write imports with filename because we have index.ts{x} files into our isolated folders.
- We can easily use absolute import and default export “components/home/HomeFooter” (need to set baseUrl in tsconfig).
- Component files like index.tsx and styles.module.scss are in the same folder and are available for quick access.
- Most things are split and isolated, but you can much faster find everything because of it.
An example from this article is available on GitHub: https://github.com/Fuchsoria/react-folder-structure/tree/master/src
If you are interested in code examples and patterns in this folder structure I will write some articles and will update the repository later.
Thanks for your time and hope I helped you a bit to organize your react app ^_^