Discover how sharing composables can save you hours of repetitive coding and bugs!
Why Sharing composables across components in Vue? - Purpose & Use Cases
Imagine you have several Vue components that all need to fetch user data and handle loading states. You copy and paste the same code into each component to do this.
Copying code everywhere makes your app hard to maintain. If you find a bug or want to change how data is fetched, you must update every component separately. This wastes time and causes mistakes.
Sharing composables lets you write the data fetching logic once in a reusable function. Then, each component can use this function easily. This keeps your code clean, consistent, and easy to update.
const loading = ref(false);
const user = ref(null);
async function fetchUser() {
loading.value = true;
user.value = await apiCall();
loading.value = false;
}import { useUser } from './composables/useUser'; const { user, loading, fetchUser } = useUser();
You can build scalable Vue apps where logic is shared cleanly, making your code easier to read, test, and maintain.
In a social media app, many components need user info. Using a shared composable means all components get the same up-to-date user data without repeating code.
Copy-pasting logic across components leads to errors and hard maintenance.
Composables let you write reusable logic once and share it easily.
This makes your Vue app cleaner, more consistent, and easier to update.
Practice
function useCounter() { const count = ref(0); return { count }; }Solution
Step 1: Understand what a composable function does
A composable is a function that returns reactive state or methods to be reused.Step 2: Identify the purpose of the example composable
The example returns a reactive count variable to share logic across components.Final Answer:
To share reusable reactive logic across multiple components -> Option DQuick Check:
Composable = reusable logic [OK]
- Thinking composables define templates
- Confusing composables with CSS styling
- Assuming composables register directives
useTimer inside a Vue component's setup() function?Solution
Step 1: Import the composable correctly
Use ES module import syntax with curly braces if composable is a named export.Step 2: Call the composable function inside setup()
CalluseTimer()to get reactive state, then destructure needed properties.Final Answer:
import { useTimer } from './composables'; const { time } = useTimer(); -> Option AQuick Check:
Import named + call function = correct usage [OK]
- Using require() instead of import
- Not calling the composable function
- Importing default when composable is named export
// composable.js
import { ref } from 'vue';
export function useCount() {
const count = ref(0);
function increment() { count.value++; }
return { count, increment };
}
// Component.vue
import { useCount } from './composable';
export default {
setup() {
const { count, increment } = useCount();
increment();
increment();
console.log(count.value);
return {};
}
}Solution
Step 1: Analyze composable logic
Count starts at 0 and increments by 1 each timeincrement()is called.Step 2: Trace component setup execution
Increment is called twice, so count.value becomes 2, then logged.Final Answer:
2 -> Option AQuick Check:
Two increments = count 2 [OK]
- Forgetting to call increment()
- Confusing ref with plain variable
- Expecting count to be 0 without increments
import { ref } from 'vue';
export function useData() {
const data = ref(null);
fetch('/api').then(res => res.json()).then(json => data = json);
return { data };
}Solution
Step 1: Check how ref is updated
Ref variables must update their.value, not be reassigned.Step 2: Identify the mistake in the fetch callback
The code assignsdata = jsoninstead ofdata.value = json.Final Answer:
Reassigning the ref variable instead of its value -> Option CQuick Check:
Update ref.value, not ref itself [OK]
- Assigning directly to ref variable
- Forgetting to handle async properly
- Confusing reactive with ref usage
Solution
Step 1: Understand independent reactive state per component
Each component needs its own fresh reactive refs to avoid shared state.Step 2: Identify correct composable pattern
Exporting a function that returns new refs each call creates isolated state per component.Final Answer:
Export a function that returns new refs each call, then import and call it in each component -> Option BQuick Check:
Function returns fresh state per call [OK]
- Sharing a single reactive object causing shared state
- Using global variables outside composables
- Confusing Vuex with composables for local state
Ready to prove it?
Pass the test and this pattern moves unknown
