Do functional components need their own separate .js file?

I’m getting started with the planning of the markdown previewer which I want to build with React.
My question is basically the title: is it best practice to put every functional component in its own separate .js which is in turn inside its own folder, or is it acceptable to write everything on the main App.js file if the application is small enough?
Thanks!

This is personal in that you should do what makes the most sense to you. I would always chuck everything in the same file until it’s getting too big then start to split it out where that makes sense rather than separate things straightaway. If it is just a very small app, then I would rather it were in one file anyway, as it’s much easier to read in that form.

React convention is one file per component, but if you do this straightaway while you’re developing an application, all that means is you’ve made it more difficult than it needs to be to change things: you should do it as a refactoring step after the design of your app settles down.

3 Likes

To extend what @DanCouper said (and as the documentation suggests) the React way is often to start with static content in a big component.

Naturally if you need to start reusing/sharing components OR if you’re beginning to add complex logic to them, it will makes sense to break them off into their own files.

In my experience, this “sixth-sense” to know when something should be extracted based on “responsibilities” and “concerns” will become stronger the more experience you have.

However, I want to mention that if you’re on a team it’s good practice to make your code (and thus organization) decisions obvious. I wouldn’t suggest housing multiple components in a single file as it may not be obvious where code comes from and lead to bugs. Instead, I would break them out into separate files and put them under an obvious folder namespace.

todos
todos/Todo
todos/TodoButton
todos/TodosSelect
2 Likes