How I Think About Splitting Up Components

How do you open up a package from Amazon?

Do you start by jabbing your finger in the side to create a hole, and then tear open from there?

Maybe you throw it against the wall until the box disintegrates, leaving behind your prize.

But unless you're dealing with a really bad merge conflict and need to take it out on something, my bet is that your approach is a little more civilized.

You find the top where the two cardboard flaps come together, and you break the seal that's holding them together.

You find the place where the box is naturally separated and use that your advantage.

Splitting up components

So much easier than randomly slashing the box with a knife, right?

Splitting up Vue components works exactly the same.

You want to find the places where the code is already starting to come apart, and give it a little nudge so it snaps cleanly.

If you've ever eaten a chocolate bar you know what I mean.

There are grooves put into the chocolate bar to create places the bar wants to break along — natural seams.

You can try to break the chocolate bar into pieces that don't follow these lines, but it usually doesn't go so well.

It's much easier to just follow the grooves that already exist in the chocolate.

Follow the already-worn path

Your Vue components also have these grooves, and you put them there.

Maybe you just don't realize it yet.

But they're there.

Here's a secret (you already know this if you've taken my Clean Components course):

The science of breaking up components into smaller ones is really the art of finding these seams and exploiting them.

"But what do these seams look like?" you may ask.

Well, you'll find them in your template, and in how your state and props interact with each other. The more two pieces of code interact with each other, the more they want to be in the same piece (or component).

(we call this cohesion, and we want high cohesion in our code)

Like the chocolate bar, the seams in your component run in between these pieces and separate them.

If you examine each prop, computed prop, watcher, method, and state in turn, eventually you'll notice that they start to clump together. They'll form clumps of code that want to be together.

You take these clumps and separate them out into their own components.

Sometimes one clump becomes one new component. Other times you'll combine several different clumps or pieces together to form a new component.

If you've been doing this for awhile you've probably developed a feel for how to do this. If you've never thought about component seams, you likely are following a process that works very similarly to this.