setup() is the entry point for Composition API logic. It runs before the component renders, receives props and a context object (emit, slots, attrs), and returns data and functions for the template.
Execution timing
- Runs once when the component instance is created (before the template renders)
propsare reactive—usetoRefsif you need to destructure without losing tracking- Return plain objects; refs unwrap in templates automatically
Compared to React function components
React mixes render and hooks in one function body that runs every render. Vue’s setup() runs once—reactive refs and computeds persist across renders. Template re-evaluation is separate from re-running all setup logic.
Organizing setup
Group related refs, computeds, and methods together—or extract composables (later lesson). Avoid massive single setup() blocks in production; colocate by feature.
Important interview questions and answers
- Q: Does setup run on every render?
A: No—only once per instance; reactivity drives subsequent updates. - Q: Can setup be async?
A: Not directly as async function—useonMounted+ async work or Suspense patterns in full apps.
Self-check
- What does
setup()return? - How do you access
emitinside setup?