Mastering React: A Developer's Guide to Structuring Your Frontend Code
Vishal Yadav

Vishal Yadav @vyan

About: I Post Daily Blogs About Full-Stack Development

Location:
India
Joined:
May 3, 2024

Mastering React: A Developer's Guide to Structuring Your Frontend Code

Publish Date: Jul 20 '24
691 51

Are you tired of sifting through a mess of React components and files? You're not alone! As your project grows, keeping your code organized becomes a real challenge. But don't worry – I've got your back. In this guide, I'll walk you through a battle-tested structure that'll make your React projects a breeze to manage.

Why Good Structure Matters

Before we dive in, let's talk about why structure is so crucial. A well-organized codebase isn't just about satisfying your inner neat freak (though that's a nice bonus). It's about:

  1. Saving time when you need to find and update components
  2. Making it easier for team members to collaborate
  3. Scaling your project without losing your mind

Trust me, your future self will thank you for taking the time to set this up right!

The React Project Structure You've Been Dreaming Of

Alright, let's get into the good stuff. Here's a structure that has served me well in countless projects:

📁src
|
|_ 📁components
|  |_ 📁Cards
|  |  |_ 📄MainCards.jsx
|  |_ 📁Buttons
|     |_ 📄PrimaryButton.jsx
|     |_ 📄SecondaryButton.jsx
|_ 📁api
|  |_ 📄Auth.js
|  |_ 📄Event.js
|_ 📁pages
|  |_ 📁HomePage
|  |  |_ 📄HomePage.jsx
|  |_ 📁LoginPage
|     |_ 📄LoginPage.jsx
|_ 📁contexts
|  |_ 📄AuthContext.js
|  |_ 📄EventContext.js
|_ 📁hooks
|  |_ 📄useAuth.js
|  |_ 📄useEvent.js
|_ 📁utils
|  |_ 📄helperFunctions.js
|  |_ 📄date.js
|_ 📁assets
|  |_ 📁images
|  |  |_ 📄logo.svg
|  |  |_ 📄background.jpg
|  |_ 📁styles
|     |_ 📄global.css
|     |_ 📄theme.js
|_ 📄App.jsx
|_ 📄index.js

Enter fullscreen mode Exit fullscreen mode

Looks neat, right? But what does it all mean? Let's break it down.

Components: Your React LEGO Bricks

Think of the components folder as your toybox of LEGO bricks. Each component is a reusable piece that you can snap together to build your app. I like to organize mine like this:

📁components
|_ 📁Cards
|  |_ 📄MainCards.jsx
|_ 📁Buttons
   |_ 📄PrimaryButton.jsx
   |_ 📄SecondaryButton.jsx
Enter fullscreen mode Exit fullscreen mode

Pro tip: Group similar components together. It'll save you hours of hunting later on!

API: Where Your Data Magic Happens

The api folder is all about data fetching. Keep your API calls separate from your UI components – your code will thank you for it. Here's what I usually include:

📁api
|_ 📄Auth.js
|_ 📄Event.js
Enter fullscreen mode Exit fullscreen mode

Pages: The Big Picture

Your pages folder houses the main views of your app. Each page is like a chapter in your app's story. For example:

📁pages
|_ 📁HomePage
|  |_ 📄HomePage.jsx
|_ 📁LoginPage
   |_ 📄LoginPage.jsx
Enter fullscreen mode Exit fullscreen mode

Contexts: Global State Made Easy

React Context is a game-changer for managing global state. I keep my context files neatly organized:

📁contexts
|_ 📄AuthContext.js
|_ 📄EventContext.js
Enter fullscreen mode Exit fullscreen mode

Hooks: Your Custom React Superpowers

Custom hooks are like your own personal React superpowers. I store mine in the hooks folder:

📁hooks
|_ 📄useAuth.js
|_ 📄useEvent.js
Enter fullscreen mode Exit fullscreen mode

Utils: Your Coding Swiss Army Knife

The utils folder is for all those handy helper functions you find yourself using again and again:

📁utils
|_ 📄helperFunctions.js
|_ 📄date.js
Enter fullscreen mode Exit fullscreen mode

Assets: Pretty Things Go Here

Keep your images, styles, and other static assets organized in the assets folder:

📁assets
|_ 📁images
|  |_ 📄logo.svg
|  |_ 📄background.jpg
|_ 📁styles
   |_ 📄global.css
   |_ 📄theme.js
Enter fullscreen mode Exit fullscreen mode

The Root Files: Tying It All Together

Finally, we have our root files that bring everything together:

  • App.jsx: The main component that sets up your app's structure
  • index.js: The entry point where your React app comes to life

Wrapping Up: Your Path to React Nirvana

There you have it – a clean, scalable structure for your React projects. Remember, this isn't a one-size-fits-all solution. Feel free to adapt it to your needs. The key is consistency.

By following this structure, you'll spend less time wrangling files and more time building awesome features. Your code will be cleaner, your team will be happier, and your projects will scale like a dream.

So, what are you waiting for? Give this structure a try in your next project. Your future self (and your teammates) will thank you!

Happy coding, and may your React projects always be organized and bug-free!

Comments 51 total

  • Vladislav Zhukov
    Vladislav ZhukovJul 20, 2024

    Thank you for these guide. You really helped me. I'm new to front-end and this guide will help me better understand how to structure projects.

  • alyouma akmal
    alyouma akmalJul 20, 2024

    Good idea.

    Previously i'm separate react folder by feature like this

    In root or src folder i create
    App.jsx
    index.jsx
    Components for all customize component
    Pages/ for all pages, in pages folder there all feature layout and each feature available folder like hook, hook folder want to take or Processor query params, route,etc for used to view folder
    view/ many component in all feature like api,view core component,hook,context,etc
    Asset/

  • Ahmed Mahmoud
    Ahmed MahmoudJul 20, 2024

    <3

  • doodleragon01
    doodleragon01Jul 20, 2024

    i would suggest "api" dir will be name as "service", so that you can actually put any kind of external services in any protocols like REST or GraphQL, RPC...

    • Akshay Bachhav
      Akshay BachhavJul 21, 2024

      yes it should be in service folder....
      same with tha utils
      utils/dataUtils every one utils must de a directory

    • Vishal Yadav
      Vishal YadavJul 22, 2024

      You can change it according to you.

  • Rense Bakker
    Rense BakkerJul 20, 2024

    Actually as the project grows larger this structure is not ideal, because the relationship between components and pages will become increasingly difficult to navigate. It's usually better to keep related things together and only make a generic components folder for components that are shared across pages. These can usually be divided into two types: ui components and layout components. In really big projects, ui components (design system) could even live in a separate repo or in a different package in a monorepo.

    • АнонимJul 20, 2024

      [hidden by post author]

    • Sam
      SamJul 21, 2024

      Agreed. Faced the same issue eventually with a multi-year enterprise project.

      We have so many hooks it takes us some time to decipher what each one does and why.

      Newer projects all have them grouped by modules with corresponding hooks and components. Makes it much easier for devs to just come in, digest that single module, and make changes.

      For more complex requirements, it is also easier to break down changes required at a higher cognitive level when you can see the different logical separations of responsibility between modules.

      The rest of the folders (API, pages, context) are project dependent. We also have a top level hook folder for utilities though.

      • Feriansyah
        FeriansyahJul 21, 2024

        Thank you for sharing your experience. I have faced a similar issue too.

        Could you provide an example of how your project structure looks with the grouped modules and corresponding hooks and components?

        Also, how do you determine whether a hook or component should be grouped into a specific module or placed at the top level? Do you have any guiding principles for this, or do you start by creating them in specific modules and move them to the top level when you find they are used in multiple cases?

        • Vishal Yadav
          Vishal YadavJul 24, 2024

          Group hooks and components by functionality or feature; promote them to the top level if they are used across multiple modules. Start specific and refactor as needed for reusability.

    • Imad
      ImadJul 22, 2024

      You can use component naming convention to separate generic (design system) components from related components like so:
      MyCoolProjectInput
      MyCoolProjectlabel
      MyCoolProjectChatInput
      MyCoolProjectChatLabel

    • Raí B. Toffoletto
      Raí B. ToffolettoJul 22, 2024

      Yes. Better to organize hooks, contexts and components per page/domain. Usually I also create a context for each page, so logic is separated from ui components. Also helps with testing.

    • Vishal Yadav
      Vishal YadavJul 24, 2024

      Yeah , it can not be used in large Size projects!

  • Ray Thurne Void
    Ray Thurne VoidJul 20, 2024

    It's better to move the context in the same file of the component that valorize it and to move the hooks along with the utils. Hooks are already identified by the use keyword.

    You only need 5 folders: components, pages/routes, assets, utils/modules, api

    The point of components and modules is to organize the code by domain rather then technical responsibility

  • Mojtaba Nayyeri
    Mojtaba NayyeriJul 20, 2024

    Good Article Thank you bro
    Have A Good Day

  • tacotoemeck
    tacotoemeckJul 20, 2024

    This approach might work for a small project but simply would not scale.

    Any production app would easily have 100s of hooks, until files and not even mentioning actual components. Navigating through something like that would simply be a nightmare.

  • Rowland
    RowlandJul 21, 2024

    Great! I use something similar too but include the CSS files of every react component in the same folder as the components.

  • Wilmela
    WilmelaJul 21, 2024

    This whole structure thing, I don't believe there is "one partner fit all" for every project. Of course your suggestion does provide some basics. So it is appreciated.

    Thanks for sharing.

    • Vishal Yadav
      Vishal YadavJul 21, 2024

      Yeah It can not be fit for all kind of projects!

  • Reuben Omaano Tetteh
    Reuben Omaano TettehJul 21, 2024

    As the project grows bigger this is really going cos a problem I think. For instance having all the styles in one folder to me is not ideal. What do you think of this approach 📁Cards => then inside the Cards Folder you have Cards.jsx and Cards.CSS.

    This way I think you can be well organized and know what Style belongs to what component.

    • Samuel Osoba
      Samuel OsobaJul 21, 2024

      Hmnnn! Looks better to me. Looks like an object approach to structure.

      This is better than those only identifying problems without suggestions.

    • Vishal Yadav
      Vishal YadavJul 22, 2024

      For larger projects, for sure it will change.

  • zoujia
    zoujiaJul 22, 2024

    👍My api folder is service😄

  • leob
    leobJul 22, 2024

    Good structure, this is more or less how I'm also doing it :)

    As other people have remarked, for a REALLY big app you might want to embrace the "module" idea, so you have (for example) a "payroll" folder (module), and below that components/pages/hooks, an "hours" folder with components/pages/hooks, etc ...

    But, for a not-so-huge app, I think this is just fine.

  • electronics.dev
    electronics.devJul 22, 2024

    Great job!

  • Abhay Chitnis
    Abhay ChitnisJul 22, 2024

    React folder structure discussion is incomplete without considering Redux and incorporating folder structure for Redux components as well.

  • Adesoji1
    Adesoji1Jul 22, 2024

    Thanks 👍🏽

  • Pra3t0r5
    Pra3t0r5Jul 22, 2024

    This grouping looks good at first but it's actually missing SOLID's colocation principle. You should keep related functionality as close as possible from each other while retaining hierarchy.

    The ideal looks like a repetition of this at any nested level. What does that mean? If you have a checkout component some levels deep on a page, all related API calls, non-reused ui components, layouts and types must sit closely to your checkout, not close to your app root.

  • Lucas Kaíque
    Lucas KaíqueJul 23, 2024

    I prefer nowadays with big projects work building scalable react applications with feature-based architecture

  • Tarun Duggempudi
    Tarun DuggempudiJul 23, 2024

    Definitely worth checking this post for any beginner who wonders "where should I create a new API folder?". These seem Basic but yet something that most of us miss while learning the technology at beginner level or a self taught programmer (at least I've missed that)

    Would be much appreciated if you can also share "How to extend your project when you add a new packages and still have the project structure organized"

    I always come across this question in my early days, when adding a package like trpc, Jotai, or adding types etc.

    Once again Thanks for sharing 👏

  • Hamam Nasrodin
    Hamam NasrodinJul 24, 2024

    where to put specific components for example I have a component slider and it is only used on the home screen?

    • Vishal Yadav
      Vishal YadavJul 24, 2024

      You can put inside

      • pages -HomePage - Slider.jsx
  • Abubakir Shavkatov
    Abubakir ShavkatovJul 24, 2024

    👎 structure, I think use fds for frontend structure

  • Silvano Norberti
    Silvano NorbertiJul 24, 2024

    Great view, I usually follow the atomic design
    When I began use it, I found a structure more readable and navigable
    I created a simplify structure, like this:

    Image description

    I removed the template section, because it's too verbose for me while developing.
    What do you think about this?

  • Okoro chimezie bright
    Okoro chimezie brightJul 25, 2024

    Nice but how about the test folder and so how will you structure the files that will be tested ?, feel free to update it thanks because in reality all prooduction applications grows so how do we handle that complexity since we must write a test before deployment ?

  • Ulyana Mykhailiv
    Ulyana MykhailivJul 26, 2024

    You know, working in the field of React development outsourcing, I often come across different codebases, and this framework looks just perfect for our needs!
    Imagine how easy it will be for newcomers to the team to understand the project with such an organization. And what a relief it is for remote collaboration - everyone immediately knows where to look for what. And scaling? But with this structure, it's just a dream, not a headache!
    I can already see how this system can speed up our development cycles and make code maintenance much easier. This is just a godsend for outsourcing React development!
    I will definitely try to apply this structure in our next project.

  • Yahaya Oyinkansola
    Yahaya OyinkansolaAug 8, 2024

    Thank you Vishal for writing this article, this has really helped me to clear a lot of issues behind creating a good folder structure in React. I am very happy with the ideas a lot of experienced devs have given in this article, but for developers like us that don't have real world experience yet, I would advice that starting from somewhere matters, you can't start building production style structure when you can't create a basic working structure, everything will change as you keep doing more work and improving the way you write code, but this article is a good foundation to start from somewhere

  • Ellen Walters
    Ellen WaltersAug 17, 2024

    offers practical strategies and best practices for organizing and optimizing React applications. This guide empowers developers to build scalable, maintainable front-end code with confidence. This article was a pleasure to read! Your way of presenting information is captivating like srdsassastatuscheck350

Add comment