3 ms·
>But the premise of the article is just not true - you do need to fundamentally understand how Svelte manages the state of your pages. I agree with this. Like
by dimmke 3y ago
>But the premise of the article is just not true - you do need to fundamentally understand how Svelte manages the state of your pages.
I agree with this. Like the example in the linked article about reactive blocks: "Svelte automatically tracks dependencies, and you only need to label a code block as reactive ($:). It'll run the code any time those dependencies change."
There's a huge caveat to that, it only does that with primitives. Which might seem obvious if you've been a developer for a while, but not at all obvious if you are a new developer. React has always taken the approach of asking you to explicitly declare state and use special methods to update it (either with setState or useState when hooks became popular) for exactly this reason, whereas in Svelte sometimes you need to actually reassign a mutated piece of state to itself so it gets picked up by this system like `foo = foo`
I think it's a reasonable tradeoff, because most state can be stored in simple primitives like strings and booleans.
Regarding lifecycle methods and Svelte, it's literally based on the DOM. Is the component leaving the DOM for whatever reason? Then onDestroy will fire. The same as you can treat onMount as a callback that fires as soon as the component is added to the DOM.
https://svelte.dev/repl/b946424a56d84a63a09856bc3df5803e?version=4.2.0 https://svelte.dev/repl/b946424a56d84a63a09856bc3df5803e?ver...
I think part of where things get tricky is that Svelte and SvelteKit are so melded together, unless you're 1. only using Svelte and not SvelteKit or 2. Are doing something really advanced and complex, you probably don't need lifecycle methods. And even then, you probably only need onMount.
A custom onDestroy can be used to manually remove something from memory, but it's mostly not needed. I agree though the docs should be better.