0
0
Vueframework~5 mins

Composable with reactive state in Vue

Choose your learning style9 modes available
Introduction

A composable with reactive state helps you organize and reuse reactive data and logic in Vue components easily.

You want to share reactive data and functions between multiple components.
You want to keep your component code clean by moving logic out.
You want to create reusable features like counters or form handlers.
You want to separate concerns in your app for easier maintenance.
Syntax
Vue
import { ref } from 'vue';

export function useExample(initialValue) {
  const state = ref(initialValue);

  function updateState(newValue) {
    state.value = newValue;
  }

  return { state, updateState };
}

Use ref to create reactive state that updates the UI automatically.

Return the reactive state and functions so components can use them.

Examples
A simple counter composable with reactive count and increment function.
Vue
import { ref } from 'vue';

export function useCounter() {
  const count = ref(0);
  function increment() {
    count.value++;
  }
  return { count, increment };
}
Using reactive for an object state with multiple properties.
Vue
import { reactive } from 'vue';

export function useUser() {
  const user = reactive({ name: '', age: 0 });
  function updateName(newName) {
    user.name = newName;
  }
  return { user, updateName };
}
Sample Program

This Vue component uses a composable useToggle to manage a reactive boolean state. Clicking the button toggles the state between ON and OFF.

Vue
<script setup>
import { ref } from 'vue';

function useToggle() {
  const isOn = ref(false);
  function toggle() {
    isOn.value = !isOn.value;
  }
  return { isOn, toggle };
}

const { isOn, toggle } = useToggle();
</script>

<template>
  <button @click="toggle" :aria-pressed="isOn">
    {{ isOn ? 'ON' : 'OFF' }}
  </button>
</template>
OutputSuccess
Important Notes

Always return reactive state and functions from composables to keep logic reusable.

Use ref for simple values and reactive for objects.

Composable functions should start with use to follow Vue conventions.

Summary

Composable functions help reuse reactive state and logic across components.

Use ref or reactive to create reactive state inside composables.

Return state and functions from composables so components can use them easily.