Johnstedt
Johnstedt

Reputation: 72

Why is project files organizing as they are in React?

I've noticed that react projects tend to be organized like this,

/src
  /actions
      userActions.js
      settingsActions.js
  /components
      userComponent.js
      settingsComponent.js
  /containers
      userContainer.js
      settingsContainer.js
  /reducers
      userReducers.js
      settingsReducers.js

coupled on type rather than functionality like,

/src
  /user
      userActions.js
      userComponent.js
      userContainer.js
      userReducers.js
  /settings
      settingsActions.js
      settingsComponent.js
      settingsContainer.js
      settingsReducers.js

Why is that? To my understanding React is good in part because it couples css, html and js together instead of having them separate. Why not do it with the file structure as well?

Upvotes: 0

Views: 132

Answers (1)

Aaditya Thakkar
Aaditya Thakkar

Reputation: 1820

There is no one true way to organize your files and directories, it varies with the opinions. But people still wonder what the best method for organising the code is.

I usually prefer the structure where containers, components, actionCreators, services and reducers are segregated. Whichever pattern you are following, you can make it more and more granular once your codebase scale up. I hope you are familiar with the idea of Presentational vs. Container components.

In the first pattern, components/ just hold the dumb stateless components that just takes props. This pattern very well support the concept of reusability. When you develop a large application, it happens quite often that you need to create a component that you definitively know you won’t reuse anywhere else, but you need it.

The containers/ have the stateful components which make API calls. Same way, if you are using redux in your application, many people tries to follow the ducks pattern where you define all the reducers in a single directory along with your root reducer, just to make things more granular and easy to access, and you don't have to jump between files to create an action.

This is just my perspective, but as I mentioned earlier, it totally depends on the use case of an application and also the opinion of the one who develops it. An alternative is to organize files by functional area as you mentioned in your second directory structure, with folders like users and settings kind of functionalities. This organization style starts off deceptively simple. But inevitably you end up with a folder common where you store very basic and common components like button, which are used all over your app, eventually you will end up with common/components and common/containers, but at one level deeper.

In short, start simple with whichever structure you want, you will eventually make it finer and finer with your use case and scale.

Upvotes: 1

Related Questions