0 day streak
javascript / expert
Snippet

Optimizing External Library Instances with markRaw

When integrating heavy third-party libraries (Mapbox, Three.js, Leaflet), making their instances reactive causes massive performance overhead because Vue tries to walk their deep internal structures. markRaw tells Vue to skip proxying the object, preserving memory and CPU cycles while still allowing the instance to be used within the component.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { markRaw, onMounted } from 'vue';
import L from 'leaflet';
export default {
setup() {
let mapInstance = null;
onMounted(() => {
// markRaw prevents Vue from making the complex Leaflet object reactive
mapInstance = markRaw(L.map('map-container').setView([51.5, -0.09], 13));
});
const flyToHome = () => {
mapInstance.flyTo([0, 0]);
};
return { flyToHome };
}
}
vue
Breakdown
1
mapInstance = markRaw(L.map(...));
Wraps the instance to ensure Vue never converts it into a Proxy.
2
let mapInstance = null;
Stored as a regular variable instead of a ref to avoid unnecessary overhead if the reference itself doesn't change.