DEV Community

Discussion on: ReactJS: Component everything or not?

Collapse
 
cullophid profile image
Andreas Møller

Start with a single component per page. If your code becomes hard to navigate you can refactor it in to more components.

It's perfectly fine to have a component with 100+ lines of code in it, and it's also fine to have many components in a file.

Good reasons to extract code into a new component:

You need the same thing on multiple pages
If you can extract the markup, state, logic you need without having to add special cases for each page.
Examples: App menu, header, footer, navigation bars.

You want to simplify your page component
You can simplify you page component by extracting some of the code into separate components.

Do this when it feels like it helps and don't be afraid of changing it back later.

Examples: Confirm delete item modal, forms, sections with complex data requirements.

Collapse
 
stereoplegic profile image
Mike Bybee

Yes, 100+ lines is fine, but much beyond that should be a candidate for splitting up even if only for readability's sake.

Collapse
 
cullophid profile image
Andreas Møller

It really depends on the specific case. If you end up having to switch between 3 different component every time you make a change, it is probably better to keep it as one.

Thread Thread
 
stereoplegic profile image
Mike Bybee • Edited

Unless it's variables and methods for that component (which could be evidence that it's time to break out into custom hooks, and/or convert a class component - which I don't write anymore if at all possible - to functional with hooks), I try to keep it on one screen without scrolling as much as possible.

Imports make it easy to follow what is where, and just because you can see it all in one file doesn't mean you're not repeating yourself somewhere else. It's also easier to see exactly what is causing errors when you have them split up.

And as I said about someone else looking toward future reuse, you never know when you might need that exact same component in another project, and your components in your current project could very well be the basis for a whole, independent component library.