mancuoj

mancuoj

Better late than never.
github
twitter

File Structure of a React Project

The overall structure is based on an article by an internet guru: Delightful React File/Directory Structure, with some modifications, and I've been using it for a while and find it quite good.

Overview#

image

index.js#

You may have noticed that each component's folder contains an index.js file, which looks like this:

export * from './App'
export { default } from './App'

It re-exports the component module, so why not put all the component code in the index? Because if all components need to be imported from the index file, our editor will be filled with various index files, making it very difficult to navigate them.

And if we don't re-export, importing the App component would look like this:

import App from '../App/App'

By "redirecting" through the index file, we can shorten it to:

import App from '../App'

components#

An example component structure is as follows:

src/
└── components/
    └── FileViewer/
        ├── Directory.js
        ├── File.js
        ├── FileContent.js
        ├── FileViewer.helpers.js
        ├── FileViewer.js
        ├── index.js
        └── Sidebar.js

hooks#

The hooks folder is used to store project-wide hooks.

If a hook is specific to a component, it should be placed in that component's folder.

I usually use this naming convention use-worker.hook.js:

  • Kebab-case instead of camel case
  • Add .hook to the file name

Of course, you can also use the conventional naming convention useWorker.js.

helpers#

The helpers folder is used to store project-wide helper functions, which are specific to the project.

If a function is specific to a component, it should be placed in that component's folder, like FileViewer.helpers.js.

utils#

The utils folder is used to store project-independent utilities, which can be understood as a personal-use-only lodash library.

constants#

The constants folder is used to store project-wide constants, most of which are related to styles.

Of course, if a constant is specific to a component, you can also place it in the component's folder, like App.constants.js.

pages#

If you are using a framework like Next.js that includes routing, you will have a pages folder.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.