Reactivity In-Depth
In the Vue world, state management at the component level is managed using ref and reactive.
If you haven’t read the fundamentals article on ref and reactive, I recommend doing that know to understand the basics.
Basic Differences
When declaring a ref variable, it can be of any data type. And it must be accessed using the “.value” syntax.
const refVar = ref(20);console.log(refVar.value); //prints 20
Reactive on the other hand will only accept type: Object. And objects have properties which will be used to access the values.
const reactiveVar = reactive({ age: 25 });console.log(reactiveVar.age); //prints 25
At the lower level, a Ref variable uses a getter and setter to listen for the reading and writing of an object while Reactive variables use a proxy because of the multiple properties you are dealing with (allowing for a more dynamic way to deal with the incoming changes).
This is Reactivity in-depth, not JavaScript. All you need to understand from the last paragraph is that ref’s deal with a simpler state of data and reactive can be used for more complex groupings because of its flexibility and how it can logically group together items.
For example, here are two ways to think about logically grouping together state data:
const Joe = reactive({ first_name: "Joe", last_name: "Daggle", age: 20, position: "Marketing Specialist", salary: 53000 department: "marketing"})
There is a problem with this though. If we choose to destructure a reactive variable, we lose reactivity and will require syntatic sugar to get this working. I don’t recommend adding even more syntantic sugar than what we are already dealing with.
However, Michael Thiessen wrote an in-depth article on ref vs reactive , and recommended using a composable that returns an object of refs which gives us the same logical grouping while giving us the benefit of being explicit and maintaining reactivity:
const Joe = useEmployee({ first_name: “Joe”, last_name: “Daggle”, age: 20, position: Marketing Specialist, salary: 53000 department: “marketing”})
Now we can use each piece of state individually.
To be continued….