How to determine when to move code into its own component?
Thought about this just now when thinking of what to add to my Pomodoro Timer. At what point or when is it beneficial to split out components into smaller pieces?
For example, my Pomdoro a timer right now is 1 component for the Pomodoro, and 1 component for the Todo list. I was thinking about adding the date, time and local weather to the nav bar which would be another component (or 2).
For small projects I imagine just keeping it like this is fine, but at what point would I want to start splitting them out?
Can use this as an example: https://github.com/callum-laing/pomodoro-timer
2 Replies
Components should only ever handle a single responsibility, a single context, a single feature, call it what you want. Basically it should do one thing only, if you can't describe it without using the word "and" it should be multiple components.
That ensures that when there's a bug somewhere you find the cause easily and you can address it easily too because the context is very narrow
Unfortunately that is the theory, in practice you often have context from other parts of the codebase leaking in and muddying the water.
And it's also a game of balance, you won't make a pause button component and a start button component if they are basically 2 sides of the same coin, you make a component that handles both at the same time.
Separation of concerns, or "what the heck is it good for?"
Having the timer and to-do list be different components makes sense, since they do two completely different thing. But what about the weather/time thing?
* Is it a "display local info" component?
* Is it two components: one for weather display the other for the local datetime?
* Is it three: one for weather, one for date, and one for time?
That last one is silly, so we'll ignore it. So it come back to "is it one or two components?" Well, how would you implement it? Is the basically the same API under the hood? No? Weather takes an external API call and local datetime is just asking the host machine? Ok, well that's my answer. One weather component and one datetime component.
Of course, it's more art than science so you do you. But that's the logic I would use to decided on a two-component solution.