Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Vue Composables useFetch, useLocalStorage: Tutorial, Examples, FAQs & Interview Tips

What are Composables?

Composables are functions that use Vue's Composition API to encapsulate and reuse stateful logic. They are Vue's equivalent of React's custom hooks. By convention, composable function names start with use.

Composables - useFetch, useLocalStorage, useDebounce
// composables/useFetch.js
import { ref, watchEffect, toValue } from 'vue'

export function useFetch(url) {
    const data    = ref(null)
    const error   = ref(null)
    const loading = ref(false)

    watchEffect(async () => {
        // Reset state
        data.value  = null
        error.value = null
        loading.value = true

        // toValue() unwraps refs or returns plain values
        const resolvedUrl = toValue(url)
        if (!resolvedUrl) return

        try {
            const res = await fetch(resolvedUrl)
            if (!res.ok) throw new Error(`HTTP ${res.status}`)
            data.value = await res.json()
        } catch (err) {
            error.value = err.message
        } finally {
            loading.value = false
        }
    })

    return { data, error, loading }
}

// Usage in component:
// const { data: users, loading, error } = useFetch('/api/users')
// const { data: post } = useFetch(computed(() => `/api/posts/${postId.value}`))
// composables/useLocalStorage.js
import { ref, watch } from 'vue'

export function useLocalStorage(key, defaultValue) {
    const stored = localStorage.getItem(key)
    const value = ref(stored ? JSON.parse(stored) : defaultValue)

    watch(value, (newVal) => {
        if (newVal === null || newVal === undefined) {
            localStorage.removeItem(key)
        } else {
            localStorage.setItem(key, JSON.stringify(newVal))
        }
    }, { deep: true })

    return value
}

// composables/useDebounce.js
import { ref, watch } from 'vue'

export function useDebounce(value, delay = 500) {
    const debouncedValue = ref(value.value)

    watch(value, (newVal) => {
        const timer = setTimeout(() => {
            debouncedValue.value = newVal
        }, delay)
        return () => clearTimeout(timer)
    })

    return debouncedValue
}

// Usage:
// const theme = useLocalStorage('theme', 'light')
// theme.value = 'dark'  // auto-saves to localStorage
// composables/useWindowSize.js
import { ref, onMounted, onUnmounted } from 'vue'

export function useWindowSize() {
    const width  = ref(window.innerWidth)
    const height = ref(window.innerHeight)

    function update() {
        width.value  = window.innerWidth
        height.value = window.innerHeight
    }

    onMounted(() => window.addEventListener('resize', update))
    onUnmounted(() => window.removeEventListener('resize', update))

    return { width, height }
}

// composables/useToggle.js
import { ref } from 'vue'

export function useToggle(initial = false) {
    const value = ref(initial)
    const toggle = () => value.value = !value.value
    const setTrue  = () => value.value = true
    const setFalse = () => value.value = false
    return { value, toggle, setTrue, setFalse }
}

// composables/useClipboard.js
import { ref } from 'vue'

export function useClipboard() {
    const copied = ref(false)

    async function copy(text) {
        await navigator.clipboard.writeText(text)
        copied.value = true
        setTimeout(() => copied.value = false, 2000)
    }

    return { copied, copy }
}

// Usage in component:
// <script setup>
// import { useWindowSize } from '@/composables/useWindowSize'
// import { useToggle } from '@/composables/useToggle'
// import { useClipboard } from '@/composables/useClipboard'
//
// const { width, height } = useWindowSize()
// const { value: isOpen, toggle } = useToggle()
// const { copied, copy } = useClipboard()
// </script>

Deep Dive: Composables in Real Projects

Understanding Composables is not just about syntax. In production applications, this topic directly affects maintainability, debugging speed, and team collaboration. Focus on readability, small reusable patterns, and predictable state flow when implementing Composables.

A practical approach is to first implement the simplest working version, then refactor into reusable pieces (components/composables/stores) only when duplication appears. This helps keep your Vue codebase clean while avoiding over-engineering.

Common Mistakes to Avoid

  • Mixing too many responsibilities in one component instead of separating logic by concern.
  • Skipping meaningful naming for variables, emits, and component props.
  • Ignoring edge cases like empty data, loading states, and error handling.
  • Optimizing too early before measuring real bottlenecks in browser devtools.
  • Not creating small test scenarios to validate behavior after each change.

Mini Practice Checklist

  1. Build a small demo focused only on Composables.
  2. Add one edge case (empty/loading/error) and handle it cleanly.
  3. Refactor repeated logic into a reusable function/composable.
  4. Add clear comments only where logic is non-obvious.
  5. Verify behavior with manual testing and Vue Devtools.
Key Takeaways
  • This chapter on Composables focuses on practical Vue 3 patterns used in real projects.
  • Prefer the Composition API with script setup for cleaner and more scalable component logic.
  • Keep components focused and move reusable logic into composables when complexity grows.
  • Use Vue Devtools to inspect component state, props, emits, and performance during development.
  • Write small experiments for each concept before applying it in production code.
  • After finishing this chapter, continue to the next related topic in the Vue roadmap.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.