Modern applications involve many DOM manipulations. Components (and elements) are constantly being removed, added, updated, etc. to deliver incredible user experiences and/or to optimize performance. Sometimes, you may need to execute code when a component is added (such as automatically focusing an input field when a form is loaded like the G-Mail login page) or when a component is removed (such as removing all event listeners associated with that element to prevent memory leaks).

Frameworks/libraries such as React.js and Svelte provide component lifecycle methods that allow developers to predictably execute code at these very moments/situations. Having such access into each stage a component undergoes provides more control over how and when the component should be rendered.

Commonly, functions can be scheduled to be invoked when these events occur in the lifecycle of a component instance:

  • Has the component been "mounted" (added to the DOM)?

  • Has the component been "unmounted" (removed from the DOM)?

  • Has the component received updated prop values?

  • Has the component's internal state been updated?

  • Has the component's DOM been updated?

Svelte Lifecycle Methods#

Svelte offers four lifecycle methods:

  • onMount - Executed when the component has been "mounted" (added to the DOM). Possible Use Cases:

    • Access DOM elements.

    • Register event listeners.

    • Fetch data from a remote API to lazy load components.

    • Load embeddable widgets/plugins from third-party libraries that require existing DOM elements (such as Leaflet.js or Google Maps).

  • beforeUpdate - Executed before the component is updated as a result of a state change.Possible Use Cases:

    • Preserve cursor position for updated text in an input field.

  • afterUpdate - Executed after the component is updated as a result of a state change.Possible Use Cases:

    • Automatically scroll to the bottom of a messenger window after a new text message is received.

  • onDestroy - Executed before the component is "unmounted" (removed from the DOM).Possible Use Cases:

    • Schedule store unsubscriptions.

    • Unregister event listeners.

    • Perform "clean up duties" for external/third-party libraries.

This is the order of phases for a cycle involving beforeUpdate and afterUpdate:

  1. The component receives updated prop values or has values in its state changed.

  2. Execute beforeUpdate.

  3. Update the DOM based on the data changes.

  4. Execute afterUpdate.

Additionally, only one lifecycle method is ran during server-side rendering:

Similarities Between Svelte and React.js Lifecycle Methods#

Coincidentally, the lifecycle methods of Svelte and React.js are quite similar:

  • getDerivedStateFromProps is called when the component receives new props or has state updated (before shouldComponentUpdate and getSnapshotBeforeUpdate). Based on the new props, it returns an object that the state should be updated with.

  • shouldComponentUpdate is called between when the component receives new props or has state updated and when rendering occurs (after getDerivedStateFromProps and before getSnapshotBeforeUpdate). It returns a boolean to determine whether to re-render the component based on the new props or state changes. These state changes may be a result of getDerivedStateFromProps.

  • getSnapshotBeforeUpdate is called just before the newly updated DOM is rendered (after getDerivedStateFromProps and shouldComponentUpdate).

Notice that all of these methods happen as soon as the component's data is updated (either new props are received or state has changed) and before any rendering occurs. As previously mentioned, beforeUpdate is also called after the props or state has been modified and before the DOM is updated. Essentially, beforeUpdate can be customized to perform the same duties as any of these three lifecycle methods.

To explore these similarities in-depth and understand why lifecycle methods are important in the development of components, let's walkthrough two versions of a simple application (one version using React.js and another using Svelte) and observe these lifecycle methods.

Preparation#

Open both demos side-by-side, and open the developer console for both.

React Demo

Svelte Demo

Svelte Demo

The application is a simple form that asks the user if they have any allergies. If they do, then an input field asking the user to mention their allergies appears beneath the radio button group.

The lifecycle methods are located in the <FormInput /> component, and each method will log a message to the console when it is executed.

Note: In the React demo, you will notice two different versions of the <FormInput /> component: src/FormInput_Class.js and src/FormInput_Hooks.js. In this post, we will be using the src/FormInput_Class.js version of the component since the useEffect hook only encompasses the lifecycle methods componentDidMount, componentDidUpdate and componentWillUnmount. Feel free to use this version of the component.

Order of Lifecycle Methods#

Mounting the Component#

Answer "Yes" to the question by clicking the "Yes" option in the radio button group.

The input field should appear beneath the radio button group, like so:

Mounting the Component

Check the developer consoles.

Developer Consoles

When a component is mounted in Svelte, it will call beforeUpdate before the initial onMount. Then, once the component has rendered, onMount is called, followed by afterUpdate. The additional beforeUpdate call is caused by the readonly this binding (bind:this) that references the input field (inputElement).

When a component is mounted in React, it will call getDerivedStateFromProps before the initial mount (before the render method is called). Then, once the component has rendered, componentDidMount (the React equivalent of Svelte's onMount) is called.

Updating Component State#

Type the letter "a" into the input field.

Updating Component State - 1

Check the developer consoles.

Developer Consoles

When a component's state is changed in Svelte, it will call beforeUpdate, followed by afterUpdate. Notice that the "X" button that appears when the input contains text is not yet rendered into the DOM when beforeUpdate is called. Once beforeUpdate finishes, the DOM is updated with the new state, and then afterUpdate is executed and has access to this newly rendered "X" button.

When a component's state is changed in React, it will call getDerivedStateFromProps (always called before the render method), followed by shouldComponentUpdate and getSnapshotBeforeUpdate. Notice that the "X" button is not yet rendered into the DOM when any of these methods are called (like beforeUpdate). Once these methods finish, the render method is called, the DOM is updated with the new state, and then componentDidUpdate (the React equivalent of Svelte's afterUpdate) is executed and has access to this newly rendered "X" button.

Inside of the input field, clear it by pressing the "X" button on the right.

Updating Component State - 2

Check the developer consoles.

Developer Consoles

Basically, the same methods are called in the exact same order. The only difference here is that the "X" button has not yet been removed from the DOM when beforeUpdate (also getDerivedStateFromProps, shouldComponentUpdate and getSnapshotBeforeUpdate) are called. Once the component re-renders and the "X" button is removed, afterUpdate (also componentDidUpdate) recognize that this button is removed.

Unmounting/Destroying the Component#

Answer "No" to the question by clicking the "No" option in the radio button group.

Unmounting/Destroying the Component

Check the developer consoles.

Developer Consoles

When a component is unmounted ("destroyed") in Svelte, it will call onDestroy, followed by the unmount method returned from onMount. Since both methods are called just before the component is unmounted, the component (and its constituent elements) are still in the DOM when these methods are called. Once these methods finish, the component will no longer exist in the DOM. Essentially, both of these methods perform the same function, but onDestroy can run inside a server-side component unlike the unmount method returned from onMount.

When a component is unmounted in React, it will call componentWillUnmount. This method, like onDestroy, is called just before the component is unmounted, so the component (and its constituent elements) are still in the DOM when it is called. Once this method finishes, the component will no longer exist in the DOM.

Next Steps#

Experiment! Apply these lifecycle methods in your Svelte applications! Build custom Svelte lifecycle methods using beforeUpdate, afterUpdate, onMount and onDestroy.

Sources#