← Back to all snippets
JAVASCRIPT

Crafting a Reusable `useToggle` Composable in Vue 3

Learn to build a simple yet powerful `useToggle` composable in Vue 3 to manage boolean states efficiently across components, enhancing code reusability.

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

/**
 * A reusable composable to manage a boolean state (true/false).
 * @param {boolean} initialValue The initial boolean value.
 * @returns {{ value: Ref<boolean>, toggle: Function, setTrue: Function, setFalse: Function }}
 */
export function useToggle(initialValue = false) {
  const isActive = ref(initialValue);

  const toggle = () => {
    isActive.value = !isActive.value;
  };

  const setTrue = () => {
    isActive.value = true;
  };

  const setFalse = () => {
    isActive.value = false;
  };

  // Return the reactive state and methods to manipulate it
  return {
    value: computed(() => isActive.value), // Use computed for read-only external access
    toggle,
    setTrue,
    setFalse
  };
}

// MyComponent.vue
<template>
  <div>
    <h1>useToggle Composable Example</h1>
    <p>Current state: {{ isOn ? 'ON' : 'OFF' }}</p>
    <button @click="toggle">Toggle</button>
    <button @click="setTrue">Set ON</button>
    <button @click="setFalse">Set OFF</button>

    <div v-if="isOn" class="message">
      This message is visible when the state is ON!
    </div>
  </div>
</template>

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

// Initialize the toggle state with an initial value (e.g., true)
const { value: isOn, toggle, setTrue, setFalse } = useToggle(true);
</script>

<style scoped>
.message {
  background-color: #e6ffe6;
  border: 1px solid #aaffaa;
  padding: 10px;
  margin-top: 15px;
  border-radius: 4px;
}
</style>
How it works: Composables in Vue 3 are functions that encapsulate reusable stateful logic. The `useToggle` composable defines a reactive boolean state (`isActive`) and methods (`toggle`, `setTrue`, `setFalse`) to manipulate it. By returning these, any component can import `useToggle` and easily manage a boolean flag with consistent logic, making the component cleaner and more focused on its UI, while the state management is handled by the composable. We use `computed` for `value` to ensure `isOn` is read-only externally, promoting immutability.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs