BeginnerCoder

Lesson 20 — Composables

Reusable logic: composables

A composable is a function (named useSomething) that creates refs and functions and returns them. Each call makes a fresh, independent set, so two counters do not share a count. It is Vue's version of React's custom hooks.

function useToggle(start = false) {
  const on = ref(start)
  return { on, toggle: () => (on.value = !on.value) }
}

Why it matters: fetching, forms and timers get written once and reused across components.

Want it another way?
Task

Finish useCounter so it also returns inc and reset. Two Apples clicks show "Apples 2", one Pears click "Pears 11", Reset apples → "Apples 0".

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Vue.js Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.