Home / Blog / Improving Reactivity in Vue.js with VueUse
Improving Reactivity in Vue.js with VueUse

Improving Reactivity in Vue.js with VueUse

Charles Allotey
Charles Allotey
Updated: December 27th 2024

If you're building a Vue.s 3 application and looking to improve your app's reactivity, VueUse is the tool you need. This powerful library offers over 200 Vue composition utilities that make it easy to integrate reactive capabilities and improve the overall performance of your projects.

In this article, we’ll explore how VueUse empowers you to create dynamic, responsive user interfaces in Vue.js with minimal code. But before diving into the powerful utilities that will elevate your Vue applications, let’s take a moment to understand what VueUse is and how it works.

What is VueUse?

VueUse Homepage Screenshot

VueUse is a utility library designed for Vue.js developers to simplify reactivity and boost app performance. With over 200 Vue composition utilities, VueUse covers a wide range of use cases, including working with browser APIs, state management, network requests, animation, and time manipulation. These Vue composables allow developers to quickly add reactive capabilities to their Vue.js applications, making it easier to build apps that respond to data changes in real time.

One of the key features of VueUse is its support for direct manipulation of reactive data. This allows developers to easily update data in real time without writing complex or error-prone code. Whether you're managing application state or reacting to external events, VueUse helps you create a seamless, dynamic user experience.

Setting Up Your Development Environment

Let's set up a Vue.js project using Vue 3 and the Composition API. If you're new to the Composition API, consider exploring Vue School's excellent Composition API course to build a strong foundation.

First, create a new Vue project using Vite:

# Create vue project with Vite
npm create vue@latest

# Navigate to project directory
cd reactivity-project

# Install dependencies
npm install

# Start dev server
npm run dev

Next, install the VueUse library:

npm i @vueuse/core

After successful installation, you should see something like this:

Vue project setup successful with VueUse installation complete

Essential VueUse Utilities

Time to go through VueUse powerful Utilities.

1. refDebounced: Optimizing Input Operations

The refDebounced utility creates a debounced version of a Vue ref, updating its value only after a specified delay without new changes. This is particularly valuable for search inputs, API calls, and performance optimization.

<template>
  <div>
    <input type="text" v-model="myText" />
    <p>{{ debounced }}</p>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { refDebounced } from "@vueuse/core";
const myText = ref("hello");
const debounced = refDebounced(myText, 1000);
</script>

Watch how the debounced value updates only after the typing pause:

Demonstration of refDebounced functionality showing delayed updates

2. useRefHistory: Time Travel Through State Changes

useRefHistory enables powerful state tracking capabilities, perfect for implementing undo/redo functionality or debugging state changes over time.

<template>
  <div>
    <form action="#" @submit.prevent="changeText()">
      <input type="text" v-model="inputText" /> 
      <button>Submit</button>
    </form>
    <p>{{ myText }}</p>
    <button @click="undo">Undo</button>
    <button @click="redo">Redo</button>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRefHistory } from "@vueuse/core";
const myText = ref("hello");
const inputText = ref("");
const { history, undo, redo } = useRefHistory(myText);

const changeText = () => {
  myText.value = inputText.value;
};
</script>

See the history navigation in action:

useRefHistory demonstration with undo/redo functionality

3. refAutoReset: Automatic State Management

The refAutoReset composable automatically resets a ref to its default value after a specified period of inactivity. This is ideal for temporary UI states, notifications, or form feedback.

<template>
  <div>
    <form action="#" @submit.prevent="changeText()">
      <input type="text" v-model="myText" /> 
      <button>Submit</button>
    </form>
    <p>{{ message }}</p>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { refAutoReset } from "@vueuse/core";
const myText = ref("");
const message = refAutoReset("default message", 5000);

const changeText = () => {
  message.value = myText.value;
};
</script>

Watch how the message automatically resets:

refAutoReset demonstration showing automatic value reset

4. refDefault: Smart Default Values

refDefault provides a clean way to handle undefined states by automatically falling back to a default value.

<template>
  <div>
    <input type="text" v-model="myText" />
    <p>{{ myText }}</p>
  </div>
</template>

<script setup>
import { refDefault } from "@vueuse/core";
const myText = refDefault("hello");
</script>

5. computedEager: Enhanced Computed Properties

computedEager offers an optimized alternative to Vue's standard computed properties, particularly useful when lazy evaluation impacts performance.

<template>
  <div>
    <p>{{ counter }}</p>
    <button @click="counter++">Increase</button>
    <p>Greater than 5: {{checkCount}} </p>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { computedEager } from '@vueuse/core';

const counter = ref(0);

const checkCount = computedEager(() => {
  return counter.value > 5;
});
</script>

See the performance improvement in action:

computedEager vs regular computed property performance comparison

The optimization becomes even more apparent in complex scenarios:

Advanced computedEager usage demonstration

Best Practices and Performance Tips

Now that you know some of the best utilities VueUse provides, we'll explore implementation best practices.

When to Use Each Utility

  • Use refDebounced for search inputs and frequent API calls
  • Implement useRefHistory for complex state management
  • Apply refAutoReset for temporary states
  • Choose computedEager when immediate computation benefits performance

Performance Considerations

  1. Set appropriate debounce intervals based on your use case
  2. Use computedEager strategically, especially for computation-heavy operations
  3. Monitor memory usage when implementing history tracking
  4. Consider the impact of auto-reset timers on application performance

Conclusion

VueUse has become an indispensable tool in the Vue.js ecosystem, offering powerful utilities that enhance application reactivity and developer productivity. By leveraging these composables, you can write more maintainable, efficient code while reducing boilerplate and improving user experience.

Additional Resources

Related Courses

Start learning Vue.js for free

Charles Allotey
Charles Allotey
Charles is a Frontend Developer at Vueschool. Has a passion for building great experiences and products using Vue.js and Nuxt.

Comments

Latest Vue School Articles

Vue.js Testing with Vue Test Utils and Vitest

Vue.js Testing with Vue Test Utils and Vitest

For inexperienced testers, Vue.js testing can be intimidating. But Vitest and Vue Test Utils makes testing Vue components a breeze!
Daniel Kelly
Daniel Kelly
Building Advanced WYSIWYG Editors with Vue and TinyMCE &#8211; A Complete Guide

Building Advanced WYSIWYG Editors with Vue and TinyMCE – A Complete Guide

Learn to integrate and customize TinyMCE in Vue with the course 'Rich Text Editing and Beyond with TinyMCE and Vue.' From basic WYSIWYG setups to advanced CMS and CRM solutions, this hands-on course equips you with the tools to build powerful content editing applications.
Daniel Kelly
Daniel Kelly

Our goal is to be the number one source of Vue.js knowledge for all skill levels. We offer the knowledge of our industry leaders through awesome video courses for a ridiculously low price.

More than 200.000 users have already joined us. You are welcome too!

Follow us on Social

© All rights reserved. Made with ❤️ by BitterBrains, Inc.