Where Should I Put My Components In The App Router?
Q: Where should I put my components in the App Router?
A: It is a good idea to keep your component files small, and that means having a lot of component files around, which can certainly cause a bunch of headaches around file management. There are a bunch of different options:
- Directly within the route directory - For small projects putting the components used in the
page.tsxfile in the same directory as thepage.tsxfile itself would be a reasonable option. The app router ignores files other thanpage.*,route.*,loader.*,error.*, etc. So putting them in the same directory isn't hurting anything. - Inside a "components" directory - In the example projects provided by Vercel they use
app/componentsdirectory to hold the component files. - Inside a hidden directory - You can also create a sub-directory prefixed with and underscore, for example
_components. The App Router will ignore this directory for routing purposes. - Inside a "route group" directory - Another option is to specify a route group directory like
(components). Route groups are a way to organize sets of routes that are actually located on route above the directory. For exampleapp/(marketing)/about/page.tsxwould serve off of/about. I used to use this(components)technique but I've moved to using_componentsinstead because I think(components)is a misuse of the route groups functionality. - In another directory altogether - If your
appdirectory is at the top level of the project then you can make a peer directory calledsrcand within thatcomponentsand you can locate your components there. If you chose to putappwithin asrcdirectory when you created the application you could put your components insrc/componentsas well.
I tend to use a combination of techniques. I put truly global components, like
"design system components" in src/components. Then when I have per-route components I put them in a _components directory within the same route directory. I may even have multiple component directories with names like _cartComponents and _headerCompenents.
There are a lot of ways to organize your components and I don't think the community has yet arrived on a "best practice". But that being said, if you tend to organize your components like this:
+ MyComponent
|--- index.tsx
|--- styles.module.css
|--- tests.ts
Which is a common practice on larger projcets then I would strongly recommend either going with src/components or app/_components because you are going to have a lot of directories.
Personally I hate this pattern because you have a ton of files with the same name only distinguished by directory. But now we have page.tsx and route.tsx so I guess I'll have to get used to figuring out a good workflow to find the page.tsx or route.tsx that I'm looking for easily.