Photo by Joan Gamell on Unsplash
Mastering React Project Structure
A Comprehensive React Guide for Seamless Development
In response to the overwhelming requests I've received, I'm delighted to unveil my preferred directory structure for projects. If you're already familiar with React but find yourself navigating through your project's complexities as it grows, this guide is tailored to help you find your way.
While I've chosen to use create-react-app with the typescript template for its simplicity, the concepts, and principles explored in this blog are versatile and can be easily adapted to other popular tools such as Vite, Webpack, and more.
Setting up Prettier
To start off, my first priority is to install prettier
as a dev dependency and configure it with a simple setup. This step is crucial to ensure smooth collaboration among multiple developers working on the same project. Having a common prettier configuration helps avoid conflicts with local configurations of other developers, and can minimize commits solely focused on formatting adjustments.
This is the prettier config I use to help get you started
{
"arrowParens": "always",
"jsxSingleQuote": false,
"printWidth": 100,
"useTabs": true,
"tabWidth": 4
}
Project Structure
I set up the directories in the src
directory as shown below
pages
directory:
This directory contains the MainRouter.tsx
file, where I define all the routes for my project, and set up their corresponding components. Each sub-directory in the pages
directory corresponds to the page and has its styles defined in the same directory.
components
directory:
This directory holds 3 more sub-directories
contexts
: Holds contexts, providers, and a specialized hook for the contexts. eg - AuthContext, ThemeContext, etchooks
: All of my custom hooks go in this directory. eg - useForm, useSearchParams, etcui
: All my UI components like Buttons, Navbar, and Inputs go in this folder.
services
directory:
This directory holds functions for any external API calls. I like to separate each resource group into its own file so it's easier to refer to or make modifications whenever necessary.
utils
directory:
This directory usually holds any util files, like storage-utils
, request-utils
, web3-utils
, etc.
assets
directory:
I keep all my static assets like images, and fonts in this directory. I prefer this over storing them in the public
folder as importing them into the application triggers React's image optimizations.
You can find the starter repo on GitHub at this link - ts-react-sass.
Thank you for reading my blog. If you wish to connect with me, you can find my socials below
Twitter - twitter.com/sarat_angajala