Join 13,567+ other Vue devs and get exclusive tips and insights delivered straight to your inbox, every week.

đź‘‹Hey friend! I work hard to send you amazing stuff each week.
— Michael
What's up?
Winter is almost here in Canada, and I'm sure it's the same in lots of other places.
We might have a couple more weeks of no snow, but I'm sure it's coming soon.
It just means more time to cozy up inside and drink lots of hot chocolate!
Here are some tips and other Vue content for you.
— Michael
It can be confusing to know whether or not to use ref or reactive.
Here are a few instances where they end up working basically the same.
When using watchEffect dependencies are tracked automatically, so there isn't much difference between ref and reactive:
// Ref — just need to access through `value` propertyconst refBurger = ref({ lettuce: true });watchEffect(() => console.log(refBurger.value.lettuce);// Reactiveconst reactiveBurger = reactive({ lettuce: true });watchEffect(() => console.log(reactiveBurger.lettuce));
Also, because refs are automatically unwrapped in the template, there is no difference there:
<template><!-- Ref -->{{ burger.lettuce }}<!-- Reactive -->{{ burger.lettuce }}</template>
If you destructure an object you'll need to convert back to refs if you want reactivity:
// Using `ref`const { lettuce } = toRefs(burger.value);// Using `reactive`const { lettuce } = toRefs(burger);
But if you have to convert everything to refs anyway, why not just use them to begin with?
If you get a variable from outside of Vue, it's nice to be able to make it reactive.
That way, you can use it in computed refs, watchers, and everywhere else, and it works just like any other state in Vue.
You can do this by using ref or reactive directly:
import { ref } from 'vue';// Can be done entirely outside of a Vue componentconst externalVariable = getValue();const reactiveVariable = ref(externalVariable);// Access using .valueconsole.log(reactiveVariable.value);
Using reactive instead:
import { reactive } from 'vue';// Can be done entirely outside of a Vue componentconst externalVariable = getValue();// Reactive only works with objects and arraysconst anotherReactiveVariable = reactive(externalVariable);// Access directlyconsole.log(anotherReactiveVariable);
If you're still on Vue 2 or using the Options API (as many are), you can use observable instead of reactive to achieve the same result.
Otherwise, to get this to work with all you need is to put it in the data section of your component:
const externalVariable = getValue();export default {data() {return {reactiveVariable: externalVariable,};}};
With reactive objects we can organize our state into objects instead of having a bunch of refs floating around:
// Just a bunch a refs :/const firstName = ref('Michael');const lastName = ref('Thiessen');const website = ref('michaelnthiessen.com');const twitter = ref('@MichaelThiessen');
Passing around a single object instead of lots of refs is much easier, and helps to keep our code organized:
// A single object to think aboutconst michael = reactive({firstName: 'Michael',lastName: 'Thiessen',website: 'michaelnthiessen.com',twitter: '@MichaelThiessen',});
There’s also the added benefit that it’s much more readable.
When someone new comes to read this code, they know immediately that all of the values inside of a single reactive object must be related somehow — otherwise, why would they be together?
With a bunch a refs it’s much less clear as to how things are related and how they might work together (or not).
However, an even better solution for grouping related pieces of reactive state might be to create a simple composable instead:
// Similar to defining a reactive objectconst michael = usePerson({firstName: 'Michael',lastName: 'Thiessen',website: 'michaelnthiessen.com',twitter: '@MichaelThiessen',});// We usually return refs from composables, so we can destructure hereconst { twitter } = michael;
This gives us the benefits of both worlds.
And if we need to add a method that modifies this state it can go in the composable. You can't do that with ref soup or a reactive object*.
*you can, but you should first stop and ask yourself if you should.
Learn how to write better composables in Vue. Use these seven patterns to manage state, logic, configuration, and input flexibility.
Check it out here: Composable Design Patterns in Vue
Discover the Vue patterns that separate good developers from great ones. Learn how senior developers use data stores, humble components, and controller patterns to build scalable modal systems that work across your entire app.
Check it out here: Junior vs Senior: Building Modals in Vue
"If there is a feature of a language that is sometimes problematic, and if it can be replaced with another feature that is more reliable, then always use the more reliable feature." — Douglas Crockford
The best way to commit something to long-term memory is to periodically review it, gradually increasing the time between reviews 👨‍🔬
Actually remembering these tips is much more useful than just a quick distraction, so here's a tip from a couple weeks ago to jog your memory.
Proxies are one of the strangest but most interesting parts of Javascript.
It's a fancy wrapper that lets us create lightweight reactivity systems like in Vue, and so much more.
Defining a proxy is simple. We just need to create a handler object, and then use it on an object:
const handler = {get(target, prop, receiver) {return 'proxied!';},};const someObj = {hello: 'world',};const proxy = new Proxy(someObj, handler);console.log(proxy.hello) // proxied!
It lets us intercept property accesses with the get "trap", so we could force any object to use our own logging method:
const handler = {get(target, prop, receiver) {return () => {if (typeof target[prop] !== "function") return;// Force the method to use our own logging methodconst consoleLog = console.log;console.log = (msg) => {consoleLog(`[${prop}] ${msg}`);};target[prop]();console.log = consoleLog;};},};const someObj = {hello() {console.log('world');}}const proxy = new Proxy(someObj, handler);proxy.hello() // [hello] world
We can also intercept when a property is set, prototypes are accessed, and many more things.
You can find a complete list on MDN:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
Michael Hoffman curates a fantastic weekly newsletter with the best Vue and Nuxt links.
p.s. I also have a bunch of products/courses: