Svelte · Senior · Question 74 of 75
How do you integrate an imperative third-party library (e.g. a chart) cleanly in Svelte 5?
<div {@attach (node) => {
const chart = createChart(node, options);
$effect(() => chart.update(data));
return () => chart.destroy();
}}></div>- ✓Correct answer: With an attachment: create the instance on mount, sync reactive data in a nested effect and destroy it in the cleanup
- 2Recreate the chart on every state change with
{#key} - 3Use
{@html}with the chart's SVG
Explanation
Only the nested effect re-runs on data changes; the instance is created once.