0
0
VueHow-ToBeginner ยท 3 min read

How to Create useCounter Composable in Vue 3

To create a useCounter composable in Vue 3, define a function that uses ref to hold the count state and returns methods to modify it. This function can then be imported and used in any component to share counter logic easily.
๐Ÿ“

Syntax

The useCounter composable is a function that returns reactive state and functions to update it. It typically uses Vue's ref to create a reactive count variable and provides methods like increment and decrement.

This pattern helps you reuse logic across components without repeating code.

javascript
import { ref } from 'vue';

export function useCounter(initialValue = 0) {
  const count = ref(initialValue);

  function increment() {
    count.value++;
  }

  function decrement() {
    count.value--;
  }

  return { count, increment, decrement };
}
๐Ÿ’ป

Example

This example shows how to create the useCounter composable and use it inside a Vue component to display and update a counter.

vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increase</button>
    <button @click="decrement">Decrease</button>
  </div>
</template>

<script setup>
import { useCounter } from './useCounter';

const { count, increment, decrement } = useCounter(5);
</script>
Output
Count: 5 [Increase] [Decrease] buttons that update the count when clicked
โš ๏ธ

Common Pitfalls

  • Not using ref or reactive for state, so updates donโ€™t trigger reactivity.
  • Returning the state object directly without accessing .value in components.
  • Mutating state outside the composable functions, which can cause unpredictable behavior.

Always keep state inside the composable and expose functions to modify it.

javascript
/* Wrong way: count is a plain number, not reactive */
export function useCounterWrong() {
  let count = 0;
  function increment() {
    count++;
  }
  return { count, increment };
}

/* Right way: count is reactive ref */
import { ref } from 'vue';
export function useCounterRight() {
  const count = ref(0);
  function increment() {
    count.value++;
  }
  return { count, increment };
}
๐Ÿ“Š

Quick Reference

useCounter composable cheat sheet:

  • ref(initialValue): creates reactive count state
  • increment(): function to increase count
  • decrement(): function to decrease count
  • Return state and functions from composable for use in components
โœ…

Key Takeaways

Create a composable as a function returning reactive state and update methods.
Use Vue's ref to make count reactive and trigger UI updates.
Keep state inside the composable and expose functions to modify it.
Import and call the composable inside components to reuse logic easily.