Understanding how to use Vuex is great and all, but I want to dig a little deeper.
You see, there are some fundamental principles for how state works.
In any frontend framework.
Including: React, Angular and Svelte — just to name a few.
Understanding these principles will help you when doing any sort of state management, including with Vuex. But today I want to highlight just one.
One thing that they all have in common.
One thing that will help us to better understand how to wrangle our state.
The First Principle
Here it is:
Data only flows down the component tree, never up.
In your Vue application, the data that's in one component can only be passed to children components. You can't pass data from a child to a parent.
Well, except for scoped slots.
But that doesn't ruin my point here.
It's a pretty simple principle. But there are some implications that come out of it that I want to explore.
If data only flows down, then where the data lives needs to be higher than where it is being used.
This includes all of the places your state is being used.
So, understanding this, you could just put all of the data in your root component. That's as high as it can possible go. If it's at the very top like this, it can be passed into any component in the app.
Of course, you'd never do this.
But why not?
Putting everything into the root component solves #1, but we get another issue:
We'll have to pass everything down the tree as props.
Too many props will just make things overly complicated and too messy.
It also breaks separation of concerns. All the components in between will know about all of these props, even if they aren't using them for anything!
But you already know this is a horrible idea.
The reason it's so bad?
Data should be close to the components it's used in. And we can keep it close by keeping data as far down the tree as possible.
Don't worry, we're going somewhere with all of this...
Implication #3 (and my final point)
We established this principle that data only flows down.
And from that we learned two things:
- Data should be placed high up in the tree
- Data should be placed low in the tree
It seems we've reached a contradiction here...
But this sort of thing happens to me when I'm reading my bible too.
I learn something new about God that seems to contradict something else I've previously learned. Really, though, I just need to dig a little deeper. I just need to think it through some more.
After thinking about this one for awhile I came to this conclusion:
Data should be placed as far down the tree as possible, while being high enough to provide the data to the components that need it.
If you can balance these two opposing constraints, you'll find the spot where the state should go.
You can think of this as the lowest common ancestor.
If it's only used in one component, stick the state in that component.
If it's used in two sibling components, stick the state in the parent.