Looking at a component itself is the primary way that we can figure out when and how to refactor it. But we can also look at how the component is used for some clues.
Specifically, we’re looking to see if there are subsets of this component where those features are only used together.
This suggests that there may be more than one component hidden inside of this one.
Let's say we have the following component:
<template><div v-if="conditional"><!-- ... --></div><div v-else><!-- ... --></div></template>
Because the v-if is at the root, we know that it's not actually adding any value to this component.
Instead, we can simplify by splitting into one component for each branch of our conditional:
<template><ComponentWhereConditionalIsTrue /><ComponentWhereConditionalIsFalse /></template>
Now, we don't need to hard-code the conditional prop — we can just use the more descriptive and specific component.
For another example, if prop1 and prop2 are only ever used together, but never with prop3 and prop4, it could mean that the functionality relying on prop1 and prop2 should be separated from the rest of the component.
In this illustration, the usage of MyComponent always uses two distinct sets of props, prop1 and prop2, or prop3 and prop4:
<MyComponent prop-1="someValue" prop-2="anotherValue" /><MyComponent prop-1="hello" prop-2="world" /><MyComponent :prop-3="34" prop-4 />
In our theoretical refactoring, we would split the component to work like this:
<FirstComponent prop-1="someValue" prop-2="anotherValue" /><FirstComponent prop-1="hello" prop-2="world" /><SecondComponent :prop-3="34" prop-4 />
Here are the steps to do this refactoring:
Learn more about this pattern in the Clean Components Toolkit.