Organize code in a small-medium react project
Orgarnize things in a small-medium react project for starters
The content in this post is based on projects created from create-react-app with typescript. When you start a new project with create-react-app things are pretty simple and you need to manage only a few files but when you work with the project for a few hours then the size of the project is getting large. It is always better to put things in an organized way so you can find things easier later and avoid some trivial bugs later. Here are my tips
src/index.tsx, src/App.tsx
These two files are the beginning of the App. In App component I usually start init logics that need to run only once like loading configs, loading auth state.
src/Routes.tsx
I usually prefer separate routes to a separate component so I can easily navigate to it when I need to check or add a new screen.
src/pages
This is the first level components folder where contains screens that users interact directly with. For example: Login, HomePage,..
src/components
This is the second level components. I usually put shared components directly under components folder. The shared components can be Layout, Header, ... things that can be shared between pages. Components that are used only in a screen will be placed under a folder with name from the screen so a LoginPage screen can have components A in components/LoginPage/A.tsx
src/context
This is to contain contexts used in screens.
src/hooks
This is shared hooks that can be used across the app.
src/hoc
My favorite setup is that hoc with init context and wrap the pages components.
src/types
types for TypeScript. For global types I prefer to extract them here
src/constants
constants to share across the app
src/repositories
This contains repositories that communicate with server for data
src/utils
multiple small utils to be shared will be here. For example idUtils for id handling like creating a new id.
src/lib
this contains integrations with other large libraries like firebase or auth.
Summary
So that is it how I usually organize code in a small react project, hope that you will find something that are helpful.
This post is originally posted here https://www.hittaducmai.se/blogs/organize-code-in-a-small-react-project