라이프사이클 함수는 컴포넌트가 화면에 마운트 되기 전 되고 난 후 등의 상태에 어떤 작업을 처리할 때 사용하는 함수라고 보시면 됩니다.
onMount: 컴포넌트가 돔에 마운트 되면 실행
onDestroy: 컴포넌트가 해제된 후 실행
beforeupdate: 컴포넌트가 마운트 되기전 실행
afterUpdate: 컴포넌트가 마운드 된 후 실행
tick: 컴포넌트 변경이 완료되면 실행(라이프사이클과 조금 성격이 다름)
svlete 라이프사이클의 전체적인 실행 순서를 보면
beforeUpdate → onMount → afterUpdate → onDestroy
그리고 부모와 자식 컴포넌트 사이에 라이프사이클의 경우 는 부모의 beforeUpdate 이후 자식 컴포넌트의 모든 라이프사이클 즉 afterUpdate 이후에 부모의 onMount 가 발생합니다. 예제는 이전에 만든 todo 앱에 라이프사이클 소스를 넣어 실행해 보도록 하겠습니다.
import { onMount, onDestroy, beforeUpdate, afterUpdate, tick } from 'svelte'
...
onMount(async() => {
console.log('child onMount')
})
onDestroy(async() => {
console.log('child onDestroy')
})
beforeUpdate(async() => {
console.log('the component is about to update');
await tick()
console.log('the component just updated');
})
afterUpdate(async() => {
console.log('child afterUpdate')
})
App beforeUpdate
TodoList.svelte:21 the component is about to update
TodoList.svelte:23 the component just updated
TodoList.svelte:12 TodoLists onMount
TodoList.svelte:27 TodoLists afterUpdate
App.svelte:103 App onMount
App.svelte:115 App afterUpdate
App beforeUpdate
TodoList.svelte:21 the component is about to update
TodoList.svelte:12 TodoLists onMount
TodoList.svelte:27 TodoLists afterUpdate
App.svelte:103 App onMount
App.svelte:115 App afterUpdate
TodoList.svelte:23 the component just updated