Search code examples
hooksveltelifecycle

Svelte: Multiple or single lifecycle hook implementation preferred?


When having to deal with multiple functions to invoke inside a svelte lifecycle hook, is there a preferred way to accomplish this?

Should all calls be put inside a single anonymous function, or should multiple lifecycle hooks be registered?

For example:

function func1() { ... }
function func2() { ... }

// Like this
onMount(() => {
    func1()
    func2()
})

// Or like this?
onMount(func1)
onMount(func2)

// Or even differently?

Is this just based on what fits better to the function content and does not matter that much in general, or is there a performance impact choosing on over the other (or any other reason)?


Solution

  • In terms of performance this probably does not matter unless you have thousands of instances.

    Otherwise it is primarily a matter of organization and dependencies. It may be more convenient to have separate hooks if they have a return function which is called on destroy. When using a single hook, those returned functions have to aggregated instead.

    E.g.

    onMount(() => {
        const cleanup1 = func1();
        const cleanup2 = func2();
    
        return () => {
            cleanup1();
            cleanup2();
        }
    });
    

    Vs. simply

    onMount(func1);
    onMount(func2);