--- title: Template Functions Must Be Pure Without Side Effects impact: MEDIUM impactDescription: Functions with side effects in templates cause unpredictable behavior on every re-render type: efficiency tags: [vue3, template, functions, performance, side-effects] --- # Template Functions Must Be Pure Without Side Effects **Impact: MEDIUM** - Functions called in templates execute on every component re-render. Functions with side effects (modifying data, API calls, logging) will cause unpredictable behavior, performance issues, and difficult-to-debug bugs. Template expressions including function calls are evaluated whenever the component updates. This makes them unsuitable for operations that should only happen once or that modify state. ## Task Checklist - [ ] Keep template functions pure (same input = same output) - [ ] Never modify reactive state inside template functions - [ ] Never make API calls or async operations in template functions - [ ] Move side effects to event handlers, watchers, or lifecycle hooks - [ ] Use computed properties for derived values instead of functions when possible - [ ] Avoid expensive computations; use computed properties for caching **Incorrect:** ```vue ``` **Correct:** ```vue ``` ## Pure Function Guidelines A pure function: 1. Given the same inputs, always returns the same output 2. Does not modify any external state 3. Does not perform I/O operations (network, console, file system) 4. Does not depend on mutable external state ```javascript // PURE - safe for templates function formatCurrency(amount, currency = 'USD') { return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(amount) } function fullName(first, last) { return `${first} ${last}` } function isExpired(date) { return new Date(date) < new Date() } // IMPURE - unsafe for templates function logAndReturn(value) { console.log(value) // I/O return value } function getFromLocalStorage(key) { return localStorage.getItem(key) // External state } function updateAndReturn(obj, key, value) { obj[key] = value // Mutation return obj } ``` ## Reference - [Vue.js Template Syntax - Calling Functions](https://vuejs.org/guide/essentials/template-syntax.html#calling-functions) - [Vue.js Computed Properties](https://vuejs.org/guide/essentials/computed.html)