- Key Takeaways
- Build Tools and Linting
- Folder Structure
- React Components
- Prefer the jsx Extension over Capital Letters
- One React Component per File
- “Smart” And “Dumb” React Components
- Avoid Large render Methods
- Always Use prop-type
- Redux
- Stand-alone JavaScript Modules
- Tests
- Conclusion
- Frequently Asked Questions on Organizing Large React Applications
In this article, I’ll discuss the approach I take when building and structuring large React applications. One of the best features of React is how it gets out of your way and is anything but descriptive when it comes to file structure. Therefore, you’ll find a lot of questions on Stack Overflow and similar sites asking how to structure applications. This is a very opinionated topic, and there’s no one right way. In this article, I’ll talk you through the decisions I make when building React applications: picking tools, structuring files, and breaking components up into smaller pieces.
Key Takeaways
- Use webpack for building projects, Babel for compiling code, and webpack-dev-server for local serving. ES Modules are preferred for importing and exporting dependencies.
- Organize code in a ‘src’ folder and categorize components based on the areas of the application where they’re used, along with a core folder for common components.
- Stick to a convention of one React component per file and always use the .jsx extension for React components. The component should always be the default export.
- Maintain a separation between “smart” components that manipulate data and “dumb” components that render data. Avoid large render methods and always use prop-type to document the names and types of properties that you expect a component to be given.
- Use Redux to manage data in applications and structure it using the Ducks system. Keep your logic out of components and test your code extensively with Jest framework. Place each test file alongside its source file to avoid confusion.
Build Tools and Linting
It will be no surprise to some of you that I’m a huge fan of webpack for building my projects. Whilst it’s a complicated tool, the great work put into version 5 by the team and the new documentation site make it much easier. Once you get into webpack and have the concepts in your head, you really have incredible power to harness. I use Babel to compile my code, including React-specific transforms like JSX, and the webpack-dev-server to serve my site locally. I’ve not personally found that hot reloading gives me that much benefit, so I’m more than happy with webpack-dev-server and its automatic refreshing of the page.
I use ES Modules, first introduced in ES2015 (which is transpiled through Babel) to import and export dependencies. This syntax has been around for a while now, and although webpack can support CommonJS (aka, Node-style imports), it makes sense to me to start using the latest and greatest. Additionally, webpack can remove dead code from bundles using ES2015 modules which, whilst not perfect, is a very handy feature to have, and one that will become more beneficial as the community moves towards publishing code to npm in ES2015. The majority of the web ecosystem has moved towards ES Modules, so this is an obvious choice for each new project I start. It’s also what most tools expect to support, including other bundlers like Rollup, if you’d rather not use webpack.
Folder Structure
There’s no one correct folder structure for all React applications. (As with the rest of this article, you should alter it for your preferences.) But the following is what’s worked well for me.
Code lives in src
To keep things organized, I’ll place all application code in a folder called src
. This contains only code that ends up in your final bundle, and nothing more. This is useful because you can tell Babel (or any other tool that acts on your app code) to just look in one directory and make sure it doesn’t process any code it doesn’t need to. Other code, such as webpack config files, lives in a suitably named folder. For example, my top-level folder structure often contains:
- src => app code here
- webpack => webpack configs
- scripts => any build scripts
- tests => any test specific code (API mocks, etc.)
Typically, the only files that will be at the top level are index.html
, package.json
, and any dotfiles, such as .babelrc
. Some prefer to include Babel configuration in package.json
, but I find those files can get large on bigger projects with many dependencies, so I like to use .eslintrc
, .babelrc
, and so on.
React Components
Once you’ve got a src
folder, the tricky bit is deciding how to structure your components. In the past, I’d put all components in one large folder, such as src/components
, but I’ve found that on larger projects this gets overwhelming very quickly.
A common trend is to have folders for “smart” and “dumb” components (also known as “container” and “presentational” components), but personally I’ve never found explicit folders work for me. Whilst I do have components that loosely categorize into “smart” and “dumb” (I’ll talk more on that below), I don’t have specific folders for each of them.
We’ve grouped components based on the areas of the application where they’re used, along with a core
folder for common components that are used throughout (buttons, headers, footers — components that are generic and very reusable). The rest of the folders map to a specific area of the application. For example, we have a folder called cart
that contains all components relating to the shopping cart view, and a folder called listings
that contains code for listing things users can buy on a page.
Categorizing into folders also means you can avoid prefixing components with the area of the app they’re used for. As an example, if we had a component that renders the user’s cart total cost, rather than call it CartTotal
I might prefer to use Total
, because I’m importing it from the cart
folder:
import Total from '../cart/total'
// vs
import CartTotal from '../cart/cart-total'
This is a rule I find myself breaking sometimes. The extra prefix can clarify, particularly if you have two to three similarly named components, but often this technique can avoid extra repetition of names.
Prefer the jsx
Extension over Capital Letters
A lot of people name React components with a capital letter in the file, to distinguish them from regular JavaScript files. So in the above imports, the files would be CartTotal.js
, or Total.js
. I tend to prefer to stick to lowercase files with dashes as separators, so in order to distinguish I use the .jsx
extension for React components. Therefore, I’d stick with cart-total.jsx
.
This has the small added benefit of being able to easily search through just your React files by limiting your search to files with .jsx
, and you can even apply specific webpack plugins to these files if you need to.
Whichever naming convention you pick, the important thing is that you stick to it. Having a combination of conventions across your codebase will quickly become a nightmare as it grows and you have to navigate it. You can enforce this .jsx
convention using a rule from eslint-plugin-react.
One React Component per File
Following on from the previous rule, we stick to a convention of one React component file, and the component should always be the default export.
Normally our React files look like so:
import React from 'react'
export default function Total(props) {
…
}
In the case that we have to wrap the component in order to connect it to a Redux data store, for example, the fully wrapped component becomes the default export:
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
export default function Total(props) {
…
}
export default connect(() => {…})(Total)
You’ll notice that we still export the original component. This is really useful for testing, where you can work with the “plain” component and not have to set up Redux in your unit tests.
By keeping the component as the default export, it’s easy to import the component and know how to get at it, rather than having to look up the exact name. One downside to this approach is that the person importing can call the component anything they like. Once again, we’ve got a convention for this: the import should be named after the file. So if you’re importing total.jsx
, the component should be imported as Total
. user-header.jsx
becomes UserHeader
, and so on.
It’s worth noting that the one component per file rule isn’t always followed. If you end up building a small component to help you render part of your data, and it’s only going to be used in one place, it’s often easier to leave it in the same file as the component that uses it. There’s a cost to keeping components in separate files: there are more files, more imports and generally more to follow as a developer, so consider if it’s worth it. Like most of the suggestions in this article, they are rules with exceptions.
“Smart” And “Dumb” React Components
I briefly mentioned the separation of “smart” and “dumb” components, and that’s something we adhere to in our codebase. Although we don’t recognize it by splitting them into folders, you can broadly split our app into two types of components:
- “smart” components that manipulate data, connect to Redux, and deal with user interaction
- “dumb” components that are given a set of props and render some data to the screen
You can read more about how we aim for “dumb” components in my blog post on Functional Stateless Components in React. These components make up the majority of our application, and you should always prefer these components if possible. They’re easier to work with, less buggy, and easier to test.
Even when we have to create “smart” components, we try to keep all JavaScript logic in its own file. Ideally, components that have to manipulate data should hand that data off to some JavaScript that can manipulate it. By doing this, the manipulation code can be tested separately from React, and you can mock it as required when testing your React component.
Avoid Large render
Methods
Whilst this point used to refer to the render
method defined on React class components, this point still stands when talking about functional components, in that you should watch out for a component rendering an unusually large piece of HTML.
One thing we strive for is to have many small React components, rather than fewer, larger components. A good guide for when your component is getting too big is the size of the render function. If it’s getting unwieldy, or you need to split it up into many smaller render functions, that may be a time to consider abstracting out a function.
This is not a hard rule; you and your team need to get a sense of the size of component you’re happy with before pulling more components out, but the size of the component’s render
function is a good measuring stick. You might also use the number of props or items in state as another good indicator. If a component is taking seven different props, that might be a sign that it’s doing too much.
Always Use prop-type
React allows you to document the names and types of properties that you expect a component to be given using its prop-types package.
By declaring the names and types of expected props, along with whether or not they’re optional, you can have more confidence that you’ve got the right properties when working with components, and you can spend less time debugging if you’ve forgotten a property name or have given it the wrong type. You can enforce this using the eslint-plugin-react PropTypes rule.
Although taking the time to add these can feel fruitless, when you do, you’ll thank yourself when you come to reuse a component you wrote six months ago.
Redux
We also use Redux in many of our applications to manage the data in our application, and how to structure Redux apps is another very common question, with many differing opinions.
The winner for us is Ducks, a proposal that places the actions, reducer and action creators for each part of your application in one file. Again, whilst this is one that’s worked for us, picking and sticking to a convention is the most important thing here.
Rather than have reducers.js
and actions.js
, where each contains bits of code related to each other, the Ducks system argues that it makes more sense to group the related code together into one file. Let’s say you have a Redux store with two top-level keys, user
and posts
. Your folder structure would look like so:
ducks
- index.js
- user.js
- posts.js
index.js
would contain the code that creates the main reducer — probably using combineReducers
from Redux to do so — and in user.js
and posts.js
you place all code for those, which normally will look like this:
// user.js
const LOG_IN = 'LOG_IN'
export const logIn = name => ({ type: LOG_IN, name })
export default function reducer(state = {}, action) {
…
}
This saves you having to import actions and action creators from different files, and keeps the code for different parts of your store next to each other.
Stand-alone JavaScript Modules
Although the focus of this article has been on React components, when building a React application you’ll find yourself writing a lot of code that’s entirely separated from React. This is one of the things I like most about the framework: a lot of the code is entirely decoupled from your components.
Any time you find your component filling up with business logic that could be moved out of the component, I recommend doing so. In my experience, we’ve found that a folder called lib
or services
works well here. The specific name doesn’t matter, but a folder full of “non-React components” is really what you’re after.
These services will sometimes export a group of functions, or other times an object of related functions. For example, we have services/local-storage.js
, which offers a small wrapper around the native window.localStorage
API:
// services/local-storage.js
const LocalStorage = {
get() {},
set() {},
…
}
export default LocalStorage
Keeping your logic out of components like this has some really great benefits:
- you can test this code in isolation without needing to render any React components
- in your React components, you can stub the services to behave and return the data you want for the specific test
Tests
As mentioned above, we test our code very extensively, and have come to rely on Facebook’s Jest framework as the best tool for the job. It’s very quick, good at handling lots of tests, quick to run in watch mode and give you fast feedback, and comes with some handy functions for testing React out of the box. I’ve written about it extensively on SitePoint previously, so won’t go into lots of detail about it here, but I will talk about how we structure our tests.
In the past, I was committed to having a separate tests
folder that held all the tests for everything. So if you had src/app/foo.jsx
, you’d have tests/app/foo.test.jsx
too. In practice, as an application gets larger, this makes it harder to find the right files, and if you move files in src
, you often forgot to move them in test
, and the structures get out of sync. In addition, if you have a file in tests
that needs to import the file in src
, you end up with really long imports. I’m sure we’ve all come across this:
import Foo from '../../../src/app/foo'
These are hard to work with and hard to fix if you change directory structures.
In contrast, putting each test file alongside its source file avoids all these problems. To distinguish them, we suffix our tests with .spec
— although others use .test
or simply -test
— but they live alongside the source code, with the same name otherwise:
- cart
- total.jsx
- total.spec.jsx
- services
- local-storage.js
- local-storage.spec.js
As folder structures change, it’s easy to move the right test files, and it’s also incredibly apparent when a file doesn’t have any tests, so you can spot those issues and fix them.
Conclusion
There are many ways to skin a cat, and the same is true of React. One of the best features of the framework is how it lets you make most of the decisions around tooling, build tools and folder structures, and you should embrace that. I hope this article has given you some ideas on how you might approach your larger React applications, but you should take my ideas and tweak them to suit your own and your team’s preferences.
Frequently Asked Questions on Organizing Large React Applications
What is the best way to structure a large React application?
The best way to structure a large React application is to follow a modular approach. This means breaking down the application into smaller, manageable components. Each component should have its own directory with its associated CSS and test files. This makes it easier to maintain and understand the codebase. Additionally, it’s advisable to separate the business logic from the UI components to ensure a clean and organized code structure.
How can I manage state in a large React application?
Managing state in a large React application can be challenging. However, libraries like Redux and MobX can help. Redux is a predictable state container for JavaScript apps that helps you write applications that behave consistently. MobX, on the other hand, is a battle-tested library that makes state management simple and scalable by transparently applying functional reactive programming. Choose the one that best fits your project requirements.
How can I handle routing in a large React application?
For handling routing in a large React application, React Router is the standard. It’s a collection of navigational components that compose declaratively with your application. It allows you to create dynamic routing applications with ease and efficiency.
How can I optimize performance in a large React application?
Performance optimization in a large React application can be achieved by implementing techniques like lazy loading, code splitting, and memoization. Lazy loading helps to load components only when they are needed, reducing the initial load time. Code splitting allows you to split your code into smaller chunks which can then be loaded on demand. Memoization is a technique used to speed up consecutive function calls by caching the result of calls with identical input.
How can I manage side effects in a large React application?
Managing side effects in a large React application can be done using middleware like Redux-Saga or Redux-Thunk. These tools allow you to handle asynchronous actions cleanly and efficiently.
How can I ensure code quality in a large React application?
Ensuring code quality in a large React application can be achieved by enforcing coding standards and guidelines. Tools like ESLint can help enforce these standards. Additionally, implementing a thorough testing strategy with unit tests, integration tests, and end-to-end tests can help maintain high code quality.
How can I handle forms in a large React application?
Handling forms in a large React application can be done using libraries like Formik or React Hook Form. These libraries help manage form state and validation with ease and efficiency.
How can I manage styles in a large React application?
Managing styles in a large React application can be done using CSS Modules or styled-components. CSS Modules allow you to write CSS that’s scoped to a single component, and not leak to any other element in the page. Styled-components, on the other hand, allows you to write actual CSS code to style your components.
How can I handle API calls in a large React application?
Handling API calls in a large React application can be done using libraries like Axios or Fetch API. These libraries provide a powerful and efficient way to make HTTP requests.
How can I handle error handling in a large React application?
Error handling in a large React application can be done using error boundaries. Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI.
I'm a JavaScript and Ruby Developer working in London, focusing on tooling, ES2015 and ReactJS.