All jobs / Frontend / web developer / Vue
Frontend / web developer interview question · 3–5 years
A useWindowSize composable adds a resize listener when it is called. After an hour of navigating, memory and handler counts keep growing.
What is wrong with the composable, and what is the contract a composable should follow?
The strongest answer
It never removes the listener. Register in onMounted and remove in onUnmounted inside the composable, call it synchronously in setup so those hooks bind to the component, and return refs
Why it works
Exactly — a composable owns its side effects: set up and tear down inside, tied to the caller’s lifecycle, state handed back as refs.
What a good answer covers
- A composable cleans up after itself.
- Add listeners in onMounted.
- Remove them in onUnmounted.
- Call composables synchronously in setup.
Answers that fall short
- Close, but not the strongest: Remove the listener in every component that uses the composable, in its own onUnmounted
It stops the leak only while every caller remembers; cleanup belongs with the code that created the listener. - Weak: Composables are garbage-collected with the component, so the leak must be somewhere else
The window holds a reference to each handler, and the handler holds the component’s state, so nothing can be collected. - Red flag: Reload the app every so often with a timer so the memory is released
A scheduled reload hides the leak from the graph and throws away the user’s work.
Who gets asked this
More Vue questions
- How do you restructure state, and what rule do you give the team?
- A five-year-old Vue codebase is on Vue 3 but written entirely in the Options API with mixins and Vuex. Some…
- A child component receives a quantity prop and has plus and minus buttons. In Vue, how should the child…
- In a Vue 3 component using script setup, you try to focus an input through a template ref at the top of setup…
- In setup, a developer writes const { count } = state, where state is a reactive object. The template shows…
- In Vue, when do you use a computed property and when a watcher?
- A user page loads its data in onMounted. Clicking from /users/1 to /users/2 changes the URL, but the page…