Thuta Learning
IntermediateWeb Developmentbeginner

Reusable Logic with Composables

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Build a composable
  • Return reactive state and functions
  • Add cleanup

Let's break it down simply

A composable is a function that packages up stateful logic using the Vue Composition API, and it's usually named starting with use. It should return state, computed values, and actions — no UI markup.

javascript
// useCounter.js
import { ref, computed } from 'vue'

export function useCounter(initial = 0) {
  const count = ref(initial)
  const doubled = computed(() => count.value * 2)
  const increment = () => count.value++
  return { count, doubled, increment }
}

// component
const { count, doubled, increment } = useCounter(5)
You should see
count = 5
doubled = 10

Try it yourself

Write a useFetch composable that returns loading, data, error, and an execute function.

ComposablesVue.js

Easy traps

  • Calling a composable outside a component, in some random scope
  • Unwrapping a reactive value into a plain value and losing reactivity

Exercise

Write a useFetch composable that returns loading, data, error, and an execute function.

You'll know it worked when: count = 5 doubled = 10

Reusable Logic with Composables | Thuta Learning