Skip to content

Instantly share code, notes, and snippets.

@marcobiedermann
Created May 19, 2022 13:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcobiedermann/224fd0f8eaae2c493b29cc9d461d50cf to your computer and use it in GitHub Desktop.
Save marcobiedermann/224fd0f8eaae2c493b29cc9d461d50cf to your computer and use it in GitHub Desktop.
React Project Structure

Folder Structure

Structure by features/domain

.
└── src
    └── features
        ├── orders
        │   ├── Orders.tsx
        │   └── order-slice.ts
        ├── products
        │   ├── Products.tsx
        │   ├── ProductsPage.tsx
        │   └── products-slice.ts
        └── user
            ├── User.tsx
            ├── Users.tsx
            ├── auth-hook.ts
            └── user-slice.ts

Structure by technology

Similar to the Model-View-Controller (MVC) pattern. Common modules are:

  • components
  • context
  • hooks
  • pages
  • templates
  • utilities
.
└── src
    ├── components
    │   ├── Orders.tsx
    │   ├── Products.tsx
    │   ├── User.tsx
    │   └── Users.tsx
    ├── context
    │   └── i18n.ts
    ├── hooks
    │   └── auth.ts
    ├── pages
    │   └── Products.tsx
    └── slices
        ├── order.ts
        ├── products.ts
        └── user.ts

Module structure

Often it makes sense to put everything around one component into a folder like tests, stories and styles.

.
└── src
    └── components
        ├── Button.stories.tsx
        ├── Button.styles.css
        ├── Button.tsx
        ├── __fixtures__
        │   └── button.ts
        ├── __tests__
        │   └── Button.test.tsx
        └── index.ts

Separation of concerns

It is recommended to separate your view (UI) from the actual business logic. Alternative names:

  • Pure

  • Dumb

  • Stateless

  • ImPure

  • Smart

  • Stateful

  • Wrapper/Container/Page

Example

// stateful
function ProductsPage() {
  const { data, loading, error } = useFetchProducts();

  if (loading) { return <Loading /> }

  if (error) { return <Error {...error} />}

  return (
    <Products products={...data} />
  )
}

// stateless
function Products(props) {
  const { products } = props;

  return (
    <ul>
      {products.map(product => (
        <Product key={product.id} {...product} />
      ))}
    </ul>
  )
}

Tools

Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment