onMounted is a component lifecycle hook for running application code after a component has been mounted into the browser DOM. It gives developers a controlled point for customizing behavior once the component's view exists onscreen. section 13.1
A small framework implementation gives the hook three responsibilities:
- Accept an optional onMounted function when defining a component, using an empty function when no hook is supplied. section 13.2
- Run the hook with the component instance as this, so it can access component state and methods. section 13.2.2
- Wrap hook execution in Promise.resolve so synchronous and asynchronous hooks share one scheduling interface. section 13.2.3
- Queue the hook instead of awaiting it during mounting, preventing slow work such as data fetching from blocking later components and the first render. section 13.3
Fetching data after mounting
An asynchronous hook can fetch data after its component exists in the DOM and then update component state: async onMounted() { const data = await fetch('https://api.example.com/data'); this.updateState({ data }) }. The hook's this value is the component instance. section 13.2.2
The scheduler stores pending hooks in a jobs queue and processes them in order. The first queued job schedules processJobs with queueMicrotask; a flag prevents duplicate scheduling. The event loop runs these microtasks after synchronous mounting finishes, before the browser's next rendering opportunity. section 13.3.3 section 13.3.4
Table 13.1 The lifecycle of a component
|
Lifecycle event
|
Code
|
Explanation
|
|---|---|---|
|
Creation
|
When the
mountDOM() function is passed a component, it instantiates it.
|
|
|
Mounting
|
component.mount(…)
|
|
|
Updating
|
||
|
Unmounting
|
Use the lifecycle table to distinguish creation, mounting, updating, and unmounting, and to locate when onMounted runs. section 13.1
