This was originally posted as a twitter thread: https://twitter.com/chrisachard/status/1239993582397816838
There is no One Way
React is a library that intentionally doesn't provide guidance about how to structure your project - and that can be really confusing for developers.
While there are no hard and fast rules however, there are some best practices - so here are 10 tips about how to structure your React projects.
First, and above all else: do what works for you and your team
There is a lot of advice out there, and much of it conflicts
Don't feel anxiety about not doing it "the right way"
If it works for you and your team - then that is the "right way"
Keep all of your components and related code in a
The other folder at the top level should be
public with static assets
Images that you are going to import inside of components should be in
Shared components go in a folder called
components, group files by function; e.g., have a folder for
form components, one for
user components, etc
Don't prematurely optimize though!
At the start it's fine to just dump all the components into the same folder. Clean it up later when you have a better idea of what your app looks like.
That includes having multiple components per file... that's OK! If you don't like it later - clean it up then.
Keep entire pages (route endpoints) in a folder called
screens (for React Native)
Inside of that, group files per page in folders
Name the main component either
MyPageXYZ.js because I don't like having 100
index.js files - but it does make for more complicated imports)
If a file's default export is a React component, capitalize that filename like the component itself
That's a signal to other devs that a component is being exported
Use absolute imports!
import MyComponent from '../../components/pages/MyComponent'
set up absolute imports and turn it into:
import MyComponent from 'pages/MyComponent'
Much nicer! 🎉
Here's the docs:
I like either css-in-js, or keeping css files next to the component they're used in
Centralizing css files in a
stylesheets folder doesn't feel great to me anymore, but your mileage may vary - do what feels best
utils folder for the random js helper functions that inevitably get created.
If you don't start with one, those functions get peppered throughout your code and make it hard to share and find
If using redux you can have separate
reducers, etc folders (that's how I do it)
Keep it in a
redux folder (sometimes called the "ducks" pattern)
Either way is fine
Either way, I do highly recommend Redux toolkit though: https://redux-toolkit.js.org/
These are all just my opinions!
Others will probably come and disagree because they've found something that works better for them - and that's awesome;
Find what works for you, and use that 🙌
Thanks for reading! If you liked this post:
🐦 You can find me on twitter: @chrisachard
💌 Or sign up for my newsletter: https://chrisachard.com/newsletter