0
0
Vueframework~8 mins

Directive hooks (mounted, updated, unmounted) in Vue - Performance & Optimization

Choose your learning style9 modes available
Performance: Directive hooks (mounted, updated, unmounted)
MEDIUM IMPACT
Directive hooks affect how and when DOM updates happen, impacting rendering speed and responsiveness.
Using directive hooks to update DOM elements on data changes
Vue
mounted(el) { el.style.color = 'red'; } updated(el, binding) { if (binding.oldValue !== binding.value) { el.style.color = binding.value; } }
Only updates style when the value changes, avoiding redundant DOM writes.
📈 Performance Gainreduces reflows to only when necessary, improving INP
Using directive hooks to update DOM elements on data changes
Vue
mounted(el) { el.style.color = 'red'; } updated(el) { el.style.color = 'red'; }
Repeatedly setting the same style in updated hook triggers unnecessary style recalculations and reflows.
📉 Performance Costtriggers 1 reflow per update even if style is unchanged
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Unconditional style update in updated hookMultiple writes per updateTriggers reflow every updateHigh paint cost[X] Bad
Conditional style update checking value changeWrites only on changeReflow only when neededLower paint cost[OK] Good
Rendering Pipeline
Directive hooks run during component lifecycle and can trigger style recalculations and layout if they modify the DOM.
Style Calculation
Layout
Paint
⚠️ BottleneckLayout (reflow) caused by DOM style changes in hooks
Core Web Vital Affected
INP
Directive hooks affect how and when DOM updates happen, impacting rendering speed and responsiveness.
Optimization Tips
1Avoid unconditional DOM writes in updated directive hooks.
2Use mounted hook for initial DOM setup only.
3Compare old and new values before updating DOM in updated hook.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of updating DOM styles unconditionally in the updated directive hook?
AIncreases bundle size significantly
BTriggers unnecessary reflows and slows interaction responsiveness
CBlocks initial page load
DCauses layout shifts during page load
DevTools: Performance
How to check: Record a performance profile while interacting with the component using directives. Look for frequent style recalculations and layout thrashing.
What to look for: High number of Layout events and long tasks during updates indicate inefficient directive hooks.