ข้ามไปยังเนื้อหา

Lifecycle

ใน Svelte 4 เราหยิบ lifecycle hook (onMount, beforeUpdate, afterUpdate) มาใช้กับอะไรก็ตามที่เกี่ยวกับ DOM หรือ timing ใน Svelte 5 $effect ครอบคลุมส่วนใหญ่ของสิ่งนั้น: $effect run หลัง DOM update, run ซ้ำเมื่อ dependency เปลี่ยน และ cleanup function ที่ return จัดการการ teardown

<script>
let count = $state(0);
$effect(() => {
document.title = `Count: ${count}`; // run หลัง mount และทุกครั้งที่เปลี่ยน
return () => { document.title = 'App'; }; // cleanup ตอน destroy / ก่อน run ซ้ำ
});
</script>

ดังนั้นก่อนหยิบ lifecycle function ให้ถามว่า effect เหมาะไหม บ่อยครั้งก็เหมาะ

lifecycle function สองตัวยังมีประโยชน์จริง:

  • onMount(fn) run ครั้งเดียวหลัง component render ลง DOM ครั้งแรก เฉพาะใน browser (ไม่เคยระหว่าง SSR) เป็นที่ที่เหมาะสำหรับ setup ที่ browser-only: วัด DOM, init canvas หรือ map library, เริ่ม interval ถ้า fn return function จะถูกเรียกตอน destroy
  • onDestroy(fn) run เมื่อ component ถูกลบ — สำหรับ cleanup ที่ไม่ผูกกับ effect ตัวใดตัวหนึ่ง (unsubscribe, clear timer)
<script>
import { onMount, onDestroy } from 'svelte';
onMount(() => {
const chart = new Chart(canvasEl); // library ที่ browser-only
return () => chart.destroy(); // cleanup ตอน unmount
});
onDestroy(() => console.log('gone'));
</script>

ความต่างสำคัญจาก $effect: onMount run ครั้งเดียวพอดี และ เฉพาะใน browser นั่นคือสิ่งที่คุณต้องการเป๊ะ ๆ สำหรับ initialization ครั้งเดียวแบบ browser-only effect ที่ไม่อ่าน reactive state ก็ run ครั้งเดียวเหมือนกัน แต่ onMount บอก intent ชัดและการันตีว่า run เฉพาะ browser

flowchart LR
  create["component ถูกสร้าง"] --> mount["onMount (browser, ครั้งเดียว)"]
  mount --> effects["$effect run หลัง DOM update"]
  effects --> effects
  effects --> destroy["onDestroy + cleanup ของ effect"]
จังหวะ lifecycle ของ component

Svelte batch การ update DOM เมื่อคุณเปลี่ยน state และต้องการให้ DOM สะท้อนการเปลี่ยนนั้น ก่อน บรรทัดถัดไป run (เพื่อวัด element หรือ focus input ที่เพิ่งแสดง) await tick() resolve เมื่อ pending changes ถูก apply แล้ว

<script>
import { tick } from 'svelte';
async function addAndScroll() {
items.push(newItem);
await tick(); // รอให้ row ใหม่อยู่ใน DOM
list.scrollTop = list.scrollHeight;
}
</script>
ใน Svelte 5 อะไรครอบคลุมเคส lifecycle-hook เดิมส่วนใหญ่?
อะไรคือจุดเด่นของ `onMount`?
`await tick()` ทำอะไร?
ควร init charting library ที่ browser-only ที่ไหน?