Reusability: Composables and Custom Hooks
7 min read
Welcome back! In this guide, we are exploring one of the most powerful features introduced in Vue 3: Composables. As applications grow, you will find yourself writing the same logic over and over again. Fetching data, managing UI toggles, listening to window resizing—these are universal tasks.
Instead of copying and pasting code until your Ctrl and V keys fall off, Vue provides a clean, scalable way to reuse stateful logic. Let's dive in.
1. The Shift to Composables (Overcoming Mixin Limitations) 🏗️
Definition
A Composable is a standard JavaScript function that leverages Vue's Composition API to encapsulate and reuse stateful logic.
A Mixin was an object containing component options (like data, methods, created) used in Vue 2 to distribute reusable functionalities for Vue components.
The Problem with Mixins
In the Vue 2 Options API era, if you wanted to share logic between two components, you used a Mixin. You would merge a separate object into your component. However, this caused massive headaches in large-scale industry applications:
- Implicit Dependencies: When a component used multiple mixins, it became nearly impossible to tell which mixin injected which data property or method. It felt like a magic trick, but the bad kind where things randomly break.
- Naming Collisions: If Mixin A and Mixin B both defined a
toggle()method, the last one loaded would overwrite the first one silently. - TypeScript Hostility: Mixins were famously difficult to strongly type, making modern enterprise development painful.
How Composables Solve This
Composables use explicit imports and standard JavaScript variable assignment. When you use a composable, you destructure exactly what you need.
Imagine you are managing an assembly line in a factory. Using Mixins is like having three separate conveyor belts dumping random car parts into one giant bucket—you have to dig through the bucket to find the steering wheel, and sometimes you accidentally grab two. Using Composables is like having a worker hand you a labeled box containing exactly one steering wheel. You know exactly what you are getting, and exactly who handed it to you.
Under the Hood
Composables work because Vue 3's reactivity system is decoupled from the component instance. The ref and reactive functions simply create JavaScript Proxy objects. As long as these Proxies are returned from your composable and accessed inside a component's setup phase, Vue can track their dependencies seamlessly.
2. Creating Your First Composable Function 🛠️
Definition
Creating a composable means writing a JavaScript function that initializes reactive state (using ref, reactive, etc.), manipulates that state, and returns it for a component to consume.
The Industry Standard
By convention, composables always start with the word use (e.g., useToggle, usePagination). This is not strictly enforced by the compiler, but it is a strict industry standard. If you name it makePagination, your senior developer might look at you with deep, profound sadness.
The Problem
You have a modal window, a dropdown menu, and a dark mode switch. All three require a boolean state (true/false) and a function to toggle that state. Writing const isOpen = ref(false) and const toggle = () => isOpen.value = !isOpen.value in every component violates the DRY (Don't Repeat Yourself) principle.
The Solution: useToggle
Let's build a highly reusable useToggle composable.
File: src/composables/useToggle.js
import { ref } from 'vue';
export function useToggle(initialValue = false) {
// 1. Define the reactive state
const isToggled = ref(initialValue);
// 2. Define the logic to mutate the state
const toggle = () => {
isToggled.value = !isToggled.value;
};
const setTrue = () => {
isToggled.value = true;
};
const setFalse = () => {
isToggled.value = false;
};
// 3. Return the state and methods
return {
isToggled,
toggle,
setTrue,
setFalse
};
}Usage in a Component: App.vue
<script setup>
// We explicitly import the composable
import { useToggle } from '@/composables/useToggle';
// We explicitly destructure what we need.
// We can also rename 'isToggled' to 'isModalOpen' to fit our context!
const {
isToggled: isModalOpen,
toggle: toggleModal
} = useToggle(false);
</script>
<template>
<button @click="toggleModal">
{{ isModalOpen ? 'Close Modal' : 'Open Modal' }}
</button>
<div v-if="isModalOpen" class="modal">
Hello from the Modal!
</div>
</template>Notice how there is no mystery? We know exactly where isModalOpen comes from. It's safe, predictable, and fully typed if we used TypeScript.
3. Managing Asynchronous State within Composables ⏳
Definition
Asynchronous state management in composables involves handling promises (like HTTP requests) while simultaneously tracking the reactive status of the request: the data payload, the loading state, and any potential errors.
The Problem
Fetching data from an API is the backbone of modern web apps. If you write raw fetch or axios calls directly inside every component, you also have to manually track isLoading and error states every single time. Doing this 50 times in an application leads to bloated, messy components.
The Solution
We can create a useFetch composable that encapsulates the entire lifecycle of an HTTP request.
File: src/composables/useFetch.js
import { ref } from 'vue';
export function useFetch(url) {
const data = ref(null);
const error = ref(null);
const isLoading = ref(false);
const execute = async () => {
// Reset state before fetching
isLoading.value = true;
error.value = null;
try {
// Simulate real-world network delay for dramatic effect
await new Promise(resolve => setTimeout(resolve, 1000));
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
data.value = await response.json();
} catch (err) {
error.value = err.message;
} finally {
isLoading.value = false;
}
};
// Auto-fetch when the composable is called (optional, but common)
execute();
return { data, error, isLoading, execute };
}Usage in a Component: UserProfile.vue
<script setup>
import { useFetch } from '@/composables/useFetch';
// Destructure the reactive variables
const { data, error, isLoading, execute } = useFetch('https://jsonplaceholder.typicode.com/users/1');
</script>
<template>
<div>
<!-- Loading State -->
<p v-if="isLoading">Loading user data... 🔄</p>
<!-- Error State -->
<p v-else-if="error" class="error">Oh no! 🚨 {{ error }}</p>
<!-- Data State -->
<div v-else-if="data">
<h2>{{ data.name }}</h2>
<p>Email: {{ data.email }}</p>
<!-- Manual Re-fetch -->
<button @click="execute">Refresh Data</button>
</div>
</div>
</template>By abstracting this into a composable, our component only cares about displaying the UI, not the complex orchestration of API states.
4. Leveraging the Ecosystem: Introduction to VueUse 🧰
Definition
VueUse is an open-source collection of essential, battle-tested Vue Composition utility functions (Composables).
The Problem
Writing a useToggle or useFetch is great for learning. But what if you need to detect when a user clicks outside a specific element? Or copy text to the clipboard? Or track the user's mouse coordinates? Or detect if the user's internet disconnected?
Writing these from scratch requires handling browser quirks, event listener cleanup (to prevent memory leaks), and complex edge cases. Reinventing the wheel wastes time and company money.
The Solution
Use VueUse. It is the industry standard utility library for Vue 3. It provides hundreds of ready-to-use composables.
Installation / Setup
To add VueUse to your Vue 3 project, run the latest command from your terminal:
npm i @vueuse/coreIndustry Example: onClickOutside
One of the most frequent UI problems is closing a dropdown menu or modal when the user clicks anywhere outside of it. With VueUse, this requires zero manual event listeners.
Component: DropdownMenu.vue
<script setup>
import { ref } from 'vue';
import { onClickOutside } from '@vueuse/core';
const isDropdownOpen = ref(false);
// We create a template ref to attach to our HTML element
const dropdownRef = ref(null);
// VueUse handles the math, event listeners, and cleanup automatically!
onClickOutside(dropdownRef, (event) => {
isDropdownOpen.value = false;
});
</script>
<template>
<div class="relative">
<button @click="isDropdownOpen = true">Options</button>
<!-- Attach the ref here -->
<div
v-if="isDropdownOpen"
ref="dropdownRef"
class="dropdown-menu"
>
<ul>
<li>Profile</li>
<li>Settings</li>
<li>Logout</li>
</ul>
</div>
</div>
</template>Under the hood, onClickOutside registers a pointerdown listener on the window when the component mounts, checks if the click's target is outside the bounds of dropdownRef, and automatically removes the listener when the component unmounts.
VueUse is practically a mandatory tool in modern Vue architecture. Always check its documentation before writing a custom composable for browser APIs or UI events!
References & Extra Reading 📚
Challenge
Your task is to create a Vue.js composable named useFetch. This composable will encapsulate the logic for fetching data from a given URL and managing the state of the request lifecycle.
Requirements:
- Define and export a function named
useFetch. - The function must accept one argument: a
urlstring. - Inside the composable, declare three reactive state variables using the Composition API:
data: Should hold the response data. Initialize it tonull.error: Should hold any fetch-related error object. Initialize it tonull.isLoading: A boolean flag to track if the request is in progress. Initialize it totrue.
- The fetching logic should execute immediately when the composable is invoked.
- Use the native
fetchAPI to make the request. You must use atry...catch...finallyblock to manage the state updates:- On success (in
try): Parse the JSON response and update thedatastate. - On failure (in
catch): Update theerrorstate with the caught error. - After completion (in
finally): SetisLoadingtofalse.
- On success (in
- The composable must return an object containing the three reactive variables:
data,error, andisLoading.
Expected result
The final code should be a single exported JavaScript function useFetch that correctly implements the specified logic.
The implementation must:
- Import
reffromvue. - Define the
useFetchfunction accepting aurlparameter. - Initialize three reactive variables using
ref():data(tonull),error(tonull), andisLoading(totrue). - Contain an asynchronous operation (e.g., within an
asyncfunction that is immediately invoked) that handles the data fetching. - Use a
try...catch...finallyblock to manage the fetch lifecycle:- In the
tryblock, it must callfetch(url), await the response, convert it to JSON usingres.json(), and assign the result todata.value. - In the
catchblock, it must assign the caught error object toerror.value. - In the
finallyblock, it must setisLoading.valuetofalse.
- In the
- Return an object containing the three reactive variables:
{ data, error, isLoading }.