Preventing Infinite Render Loops from Inline Object Props
Managing shared state between parent and child components requires strict attention to object reference stability. The following component architecture demonstrates how inline propp assignments can trigger a infinite rendering cycle:
<!-- DataTable.vue -->
<template>
<div>
<span>Current Filters: {{ queryConfig }}</span>
<ul v-if="records.length">
<li v-for="record in records" :key="record.id">{{ record.title }}</li>
</ul>
</div>
</template>
<script>
export default {
props: {
queryConfig: { type: Object, default: () => ({}) },
records: { type: Array, default: () => [] }
},
watch: {
queryConfig() {
this.records.length = 0
this.fetchRemoteData()
}
},
mounted() {
this.fetchRemoteData()
},
methods: {
fetchRemoteData() {
setTimeout(() => {
const payload = this.mockApiCall(this.queryConfig)
payload.forEach(item => this.records.push(item))
}, 15)
},
mockApiCall(cfg) {
return [{ id: 1, title: 'Alpha' }, { id: 2, title: 'Beta' }]
}
}
}
</script>
Binding this component in a parent template with a inline object literal causes the UI thread to lock:
<!-- ParentContainer.vue -->
<template>
<DataTable :query-config="{}" :records="itemStore" />
</template>
<script>
export default {
data() {
return {
itemStore: []
}
}
}
</script>
The freeze originates from a recursive update chain. Vue's scheduler detects mutations to the records array and schedules a parent re-render. During template compilation, the inline :query-config="{}" syntax instantiates a fresh JavaScript object on every render pass. The child component's watcher evaluates the new object reference as a state change, clears the dataset, and initiates another network simulation. This cycle repeats continuously within the same macro-task.
Stabilizing the prop reference by declaring the configuration object inside the parent's reactive state breaks the loop:
<!-- ParentContainer.vue -->
<template>
<DataTable :query-config="filterState" :records="itemStore" />
</template>
<script>
export default {
data() {
return {
filterState: {},
itemStore: []
}
}
}
</script>