Exclusive tips every week

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

    Picture of Michael Thiessen

    đź‘‹Hey friend! I work hard to send you amazing stuff each week.

    — Michael

    I really love and enjoy reading these emails.

    You are one of the most pro VueJS devs I know, and I am happy that you share this knowledge.

    Fabian Beer

    Here's my latest newsletter

    🔥 (242) When ref and reactive work the same, how to make a variable created outside of Vue reactive, and more

    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

    🔥 When ref and reactive work the same

    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` property
    const refBurger = ref({ lettuce: true });
    watchEffect(() => console.log(refBurger.value.lettuce);
    // Reactive
    const 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?

    🔥 How to make a variable created outside of Vue reactive

    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 component
    const externalVariable = getValue();
    const reactiveVariable = ref(externalVariable);
    // Access using .value
    console.log(reactiveVariable.value);

    Using reactive instead:

    import { reactive } from 'vue';
    // Can be done entirely outside of a Vue component
    const externalVariable = getValue();
    // Reactive only works with objects and arrays
    const anotherReactiveVariable = reactive(externalVariable);
    // Access directly
    console.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,
    };
    }
    };

    🔥 Avoid Ref Soup

    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 about
    const 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 object
    const michael = usePerson({
    firstName: 'Michael',
    lastName: 'Thiessen',
    website: 'michaelnthiessen.com',
    twitter: '@MichaelThiessen',
    });
    // We usually return refs from composables, so we can destructure here
    const { 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.

    📜 Composable Design Patterns in Vue

    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

    📜 Junior vs Senior: Building Modals 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

    đź’¬ More Reliable Features

    "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

    đź§  Spaced-repetition: Proxy Basics

    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 method
    const 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.

    Sign up for it here.

    p.s. I also have a bunch of products/courses:

    Here's what others are saying

    I'm starting to think that your newsletter is one of the best things that happened to me this year. I just love these emails.
    Stanislaw Gregor
    I'm somewhere in the upper-middle level at Vue, and I never miss an email you and always find something cool when reading!
    Eduard Climov
    This is the first time where I'm actually enjoying email newsletters. I like your format a lot.
    Fahmi Alfituri
    You have great content in your emails. I seriously learn something from every one of them.
    Titus Decali
    Just wanted to say I enjoy these emails. They encourage me to constantly improve my craft. Fantastic work.
    Joe Radman
    Thanks for another beautiful tip 🙏
    Victor Martins Onuoha
    Loving these, and the spaced repetition.
    Mark Goldstein
    I really enjoy reading your emails, because I love Vue. Thanks for these emails.
    Arturo Espinoza
    I really love and enjoy reading these emails. You are one of the most pro VueJS devs I know, and I am happy that you share this knowledge.
    Fabian Beer
    THANK YOU! I did not know about the deep property, so I assumed you simply couldn't watch objects.
    Darryl Noakes
    I really must say you are doing a really great job. Now I am aware of a cleaner and more performant way to use Tailwind. Thanks a lot!
    Henry Eze
    Thank you so much, I really enjoy and appreciate your emails.
    Carlos Gonzalez
    Thanks for sharing great Vue tips.
    Fernando Navarro
    I really enjoy these tips.
    Martin H
    Thank you so much for the weekly Vue education. Thanks and live on longer to educate us more.
    Kabolobari Benakole
    I look forward to your emails every week. This week was something I knew, but I like to be reminded of. Thanks for keeping it up!
    Nathan Strutz
    Thank you for your weekly emails. I always look forward to learning a new tip about Vue or at least relearning old tips :)
    Colin Johnson
    I have really been enjoying your weekly emails, and I also got my two team members to join in on the fun as well.
    Keith Dawson
    Thank you for your newsletter, your explanations have very concise examples and I like it.
    Nicolas Decayeux
    Thanks A LOT for your great work!!! One of the few newsletters that I let pass!
    Martin Tillmann

    Want to level up your Vue skills?

    With over two million reads and 11,067 subscribers, you've come to the right place.

    Subscribe now to get exclusive insights and tips every week.