Tutorials on Componentwillunmount

Learn about Componentwillunmount from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

Svelte Lifecycle Method - onDestroy

In Svelte, a component's onDestroy lifecycle method is called before the component is removed from the DOM. For example, if you have a component that is wrapped within an {#if} block and it is currently rendered to the DOM, then when this block's conditional statement evaluates to false , the component will be unmounted from the DOM, at which point onDestroy will be called. Being able to schedule a callback to run at this phase of a component's lifecycle ensures that cleanup-related operations can be ran and previous application states can be resumed. Here's a template of how the onDestroy lifecycle method is used inside of a component: Compared to the function returned from onMount , there are specific reasons for using onDestroy : As a vital lifecycle method, onDestroy covers a wide diversity of use cases such as... Below, I'm going to show you: When a modal dialog is closed, the focus should return back to the element that opened the modal dialog. Not doing so would hurt the experience of users who rely on keyboards and/or assistive technologies to navigate through webpages. To rescue the focus: Visit this simple Svelte REPL demo to see how to refocus a previous element using the onDestroy lifecycle method: Demo - onDestroy Lifecycle Method - Modal ( Modal.svelte ) When the "Open Modal" button is clicked, it sets the isModalOpened flag to true , which causes the <Modal /> component to be rendered to the page. When an instance of the <Modal /> component is created, its <script /> block is executed, and previouslyFocused is set to document.activeElement , which references the most-recently focused element (the "Open Modal" button). Notice that the "Close Modal" button in the modal dialog is focused due to its autofocus attribute. When you click the "Tab" key, the focus is trapped within the modal dialog (each press moves the focus to each link, followed by the "Close Modal" button, and back, repeating in a cycle), which prevents the focus from escaping the modal dialog. When you press the "ESC" key or click the "Close Modal" button, then the "close" event is dispatched, which will execute the closeModal function, set the isModalOpened flag to false and remove the modal dialog from the DOM. Before the modal dialog is unmounted, the callback passed to onDestroy will be ran. The focus will resume back to the previously focused element, the "Open Modal" button. Note : In Firefox and Safari, document.activeElement references the <body /> element in an <iframe /> element (where the Svelte REPL displays the result of the Svelte code). In the demo, a reference to the "Open Modal" button is passed to the <Modal /> component as a prop, and it is manually used as the previously focused element if document.activeElement references the <body /> element. Removing event listeners is necessary for avoiding memory leaks in older browsers that don't automatically garbage-collect event handlers of removed DOM elements. A common pattern for registering and unregistering event listeners in Svelte is to perform these actions during the onMount and onDestroy lifecycle methods respectively. Visit this simple Svelte REPL demo to see how to remove event listeners in your Svelte application using the onDestroy lifecycle method: Demo - onDestroy Lifecycle Method - Removing Event Listeners (Window Resize) ( WindowResize.svelte ) Resizing the window updates the printed width value. By debouncing the event handler, the resize event listener will only call the event handler after the resize event has stopped firing for 300ms. Limiting the rate at which the event handler is executed will yield performance gains, especially in much larger applications. To trigger the onDestroy lifecycle method, press the "Toggle" button to toggle off the <WindowResize /> component. This will remove the registered resize event listener on the window object. If, instead, the event listener was binded to an element within the component, then the event listener can be binded to the element in onMount since the element will have been rendered by the time onMount is called. Likewise, the event listener can be removed from the element in onDestroy since onDestroy occurs just before the element is removed from the DOM, which means the element still exists when removing this event listener. To understand how a UI change can affect a user's engagement with your application, you might collect a set of metrics, such as bounce rate and average session duration, via Google Analytics or software custom-built to log this information. A simple metric to integrate into your application is tracking how long a user stays on a page. A rudimentary implementation of this would involve starting a timer the moment the user visits the page, and then stopping the timer the moment they exit the page. Visit this simple Svelte REPL demo to see how to log user activity in your Svelte application using the onDestroy lifecycle method: onDestroy Lifecycle Method - Logging User Activity ( RedditArticle.svelte ) In this example, each tab represents a "subreddit," a topic-specific, online community on Reddit ( r/science , r/technology and r/worldnews ). Clicking on any of these tabs will display a list containing the most popular articles for the corresponding subreddit. The <RedditArticles /> component is mounted anytime the user clicks on any of the subreddit tabs. Upon switching from one subreddit to another, the current <RedditArticles /> component will be unmounted, and a new <RedditArticles /> component will be mounted. The subreddit prop is passed to ensure the articles for the currently selected subreddit are loaded. When an instance of the <RedditArticles /> component is created, this represents the user landing on a new "page," and a timer begins to mark this ( let startTime = performance.now(); ). Once the user leaves the "page" (switching to a new subreddit), the onDestroy lifecycle method is called, and the difference between the time at which the component is unmounted and the recorded start time is calculated. This difference represents how long the user was on this subreddit before leaving. After performing this calculating, the difference can be sent to an API endpoint to be stored. All of the data collected can then be aggregated and viewed inside of a dashboard. Typically, in component-based architectures, data flows downwards from parents to children (unidirectional). In Svelte, stores allow data to be shared between components, regardless of their relationship in the component hierarchy. A store contains a subscribe method that notifies components of changes to the store's value. When the subscribe method is executed, an unsubcribe method is returned, which cancels a component's subscription to a store when called. Visit this simple Svelte REPL demo to see how to unsubscribe from a Svelte store subscription using the onDestroy lifecycle method: onDestroy Lifecycle Method - Scheduling Store Unsubscriptions ( RedditArticles.svelte ) In this example, the "Logging User Activity" demo has been repurposed with the <Subreddits /> component (the tabs) and the <RedditArticles /> component (the list of subreddit articles) both subscribed to a store named reddit . ( store.js ) currentSubreddit represents the currently selected subreddit (by default, it is r/science). Because the value of currentSubreddit can be modified, this store is a writable store, which means two additional methods are provided alongside the subscribe method: set (sets a new value for the store and synchronously executes every active subcription method of the store) and update (updates a value based on the current value in the store). For convenience, a custom method, setCurrentSubreddit , is made available, and it directly updates the currentSubreddit value. All components subscribed to the store will see the changes. In this case, both the <App /> and <RedditArticles /> components are subscribed to the store for changes to currentSubreddit . Imagine a scenario in which a component is mounted/unmounted many times throughout the lifetime of the application. If unsubscribe is not called upon unmounting the component, then its corresponding subscription will still be alive and will be executed upon future updates to the store even when the component the subscription is tied to has been unmounted. Try this out by commenting out the unsubscribe function call in the <RedditArticles /> component's onDestroy and adding a console.log() statement inside of the subscription function. As you switch tabs from one subreddit to another, watch as more and more messages are printed inside of the console. With so many subscriptions still in memory and not garbage-collected, eventually, this will cause a memory leak. To avoid this situation, the unsubscribe method must be called inside of onDestroy lifecycle method. Note : Subscribing to the store and adding a call to the unsubscribe method inside of many components that rely on the store can become tedious and resemble repetitive boilerplate code. Instead, just import the store and prefix a store value with a $ to auto-subscribe to it. The auto-subscription shorthand will allow components to auto-subscribe to the store and automatically unsubscribe from it when the component is destroyed. Check out the <Subreddits /> component for an auto-subscription example. ( Subreddits.svelte ) For third-party libraries such as Leaflet.js that embed interactive maps into an application, the provide methods for "cleaning-up" when they are removed from the DOM. For example, in the case of Leaflet.js, the remove method destroys the map and its layers and clears all of their corresponding event listeners. Visit this simple Svelte REPL demo to see how to clean-up an embedded Leaflet map in your Svelte application using the onDestroy lifecycle method: onDestroy Lifecycle Method - Clean-Up External/Third-Party Libraries ( LeafletMap.svelte ) When the map is toggled on, the <LeafletMap /> component's onMount lifecycle method is called and initializes a new map on a specified container element. Additionally, a marker icon is displayed, and an event listener is added to this icon. Whenever the icon is clicked, a popup opens above it. Once the map is toggled off, the <LeafletMap /> component's onDestroy lifecycle method is called and destroys the map and the marker and clears all of their corresponding event listeners such as zooming in the map, the opening of the marker icon's popup on clicking, etc. When server-side rendering a Svelte application, only one lifecycle method is called: onDestroy . Particularly, onDestroy is called after the application is rendered. For example, when building the static version of a Sapper application via npm run export , only onDestroy is called. To verify this, simply add a console.log statement into each lifecycle method call and observe the outputted logs in the CLI. ( src/routes/index.svelte ) If you have built React applications, then you will have probably noticed how similar onDestroy is to componentWillUnmount . Try rewriting some of those components that use componentWillUnmount as Svelte components that use onDestroy . If you want to learn more about Svelte, then check out Fullstack Svelte :

Thumbnail Image of Tutorial Svelte Lifecycle Method - onDestroy

Comparing Lifecycle Methods - React.js and Svelte

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: Svelte offers four lifecycle methods: This is the order of phases for a cycle involving beforeUpdate and afterUpdate : Additionally, only one lifecycle method is ran during server-side rendering: Coincidentally, the lifecycle methods of Svelte and React.js are quite similar: 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. Open both demos side-by-side, and open the developer console for both. React 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. 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: Check the 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. Type the letter "a" into the input field. Check the 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. Check the 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. Answer "No" to the question by clicking the "No" option in the radio button group. Check the 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. Experiment! Apply these lifecycle methods in your Svelte applications! Build custom Svelte lifecycle methods using beforeUpdate , afterUpdate , onMount and onDestroy .

Thumbnail Image of Tutorial Comparing Lifecycle Methods - React.js and Svelte

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More