Tutorials on Lifecycle Method

Learn about Lifecycle Method 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

Vue 3 - The Composition API (Part 1)

As the most starred open source, JavaScript library/framework repository on GitHub, Vue.js has become a top three front-end technology alongside React.js and Angular in terms of popularity, usage, ecosystem activity and developer satisfaction. Compared to React.js and Angular, Vue.js is incrementally adoptable and provides a declarative API that resonates with AngularJS developers. Evan You , the author of Vue.js, explained the original concept of Vue.js as extracting the best parts of AngularJS, such as directives (i.e., v-if and v-show ), and building a lightweight, flexible alternative. Building large Vue.js applications requires composing components together with state management (i.e., Vuex ) and routing (i.e., Vue Router ) libraries. In September 2020, the Vue.js team officially released Vue 3, which welcomed a number of improvements and new features: Particularly, the Composition API of Vue 3 has been met with controversy due to its resemblance to React hooks and its philosophical divergence from the Options API , which emphasizes separation of concerns by defining component logic within specific options ( data , props , computed , methods , etc.). For those who prefer the Options API, unlike other major version upgrades that introduce incompatible changes, the Composition API will not break existing Vue components using Options API (" purely additive "). Although it offers similar logic composition capabilities as React hooks, the Composition API leverages Vue's reactivity system to circumvent several of React hooks' issues. To understand why the Composition API's new approach for creating components allows developers to better reason about and maintain large components, we will need to... A single file component consists of HTML-based markup ( <template /> ), CSS-based styles ( <style /> ) and JavaScript-based logic ( <script /> ), all self-contained within a single .vue file. Example : The following component will display "Hello World!" as red text. Note : The scoped attribute applies to CSS only to the elements within the current component. In the above example, the data function returns an object that represents the component's data. Vue converts each data property to a Proxy , which makes the state reactive by allowing for proper this bindings and tracking/triggering changes. The object returned by data contains a single property, greeting , which has a value of "Hello World!" and is rendered within the <p /> element's mustaches ( {{ ... }} ). For a one-time interpolation, use the v-once directive. Note : In previous versions of Vue, the reactivity system used Object.defineProperty , not Proxy . Now that you are familiar with the base structure of a component, let's explore a slightly more complex component. Open the CodeSandbox demo here . In this demo, let's look at a component that represents a simple accessible modal. When the modal is opened, the focus should be trapped within it. Elements within the modal should be "tabbable." When the modal is closed, the focus should return back to the element responsible for opening the modal. ( src/components/Modal.vue ) ( src/App.vue ) Here, the <Modal /> component is defined using the Options API , which organizes component logic into specific options. The initialization of internal state ( data ), the passed props ( props ), the emitted custom events ( emits ), the available instance methods ( methods ) and lifecycle hooks ( beforeMount , mounted and unmounted ) are clearly separated from one another. For an option to access values/methods defined within other options, those values/methods must be referenced via the this keyword, which refers to the component instance itself. Below is a list of commonly used options: Note : Do not use arrow functions when defining a watcher or methods / computed method. Otherwise, the this keyword will not reference the component instance. As a component grows larger with more new features, it increasingly becomes more difficult to maintain and reason about the component, especially when the logic of each feature is fragmented over the individual options. The RFC for the Composition API provides a side-by-side comparison of how logic related to a feature (also called a logical concern in the official documentation ) is distributed throughout a component's code. Each logical concern is identified by a unique color. Notice how neatly grouped each feature's logic is when using the Composition API. By restricting component logic to specific options, it adds a mental tax by requiring us to constantly switch from one block of code to another to understand/work on any single feature of a component. Also, it limits our ability to extract and reuse common logic between components. This is the primary motivation behind the Composition API. By exposing Vue's core capabilities, such as reactivity and lifecycle hooks, as standalone functions, the Composition API can use these functions within the setup component option, which is executed before the component is created (formerly the created lifecycle hook option) and serves as the component's main entry point. Let's revisit the simple accessible modal, but this time, create the component using the Composition API. Open the CodeSandbox demo here . ( src/components/Modal.vue ) ( src/App.vue ) All of the logic that was previously handled in multiple options of a Vue component is now contained within a single option, setup . Functions that behave similar to those options can be imported as named exports from vue and called anywhere within the setup function. For example, the lifecycle hook options beforeMount , mounted and unmounted can be replaced using the onBeforeMount , onMounted and onUnmounted methods in setup respectively. This allows component logic to be structured and arranged flexibly. The reactive data returned by the data option can be replaced using the ref and reactive methods in setup . The ref method accepts a default value and returns a reactive ref object that can be safely passed throughout the entire application. Because this object is mutable, the value can be directly modified. To reference this value, access this object's .value property. ref is commonly used for establishing reactivity for a single primitive value. To establish reactivity for an entire object, use the reactive method. setup exposes two arguments, props and context . props contains the props passed from a parent component. They are reactive and automatically updated whenever new props are passed in. To properly destructure props , which means still preserving each props reactivity after destructuring, use the toRefs method. context contains three properties: Within the context of the <Modal /> component: Although the component's methods are defined within the setup option, the component's template can only access these methods when they placed within the object returned by setup . This also applies to ref and reactive values, which are automatically unwrapped to allow the template to access their values without having to reference .value . The close method and modalRef ref are made available to the <Modal /> template. The close method is set to the @click shortcut directive, so when the user clicks this button, the "close" event will be emitted by the component, which will trigger the function set to @close on the <Modal /> component within the <App /> parent component (the closeModal method). When set to the <div class="model" /> element's ref , modalRef will reference this DOM element. A component built with the Composition API has its setup function only called once during its entire lifetime, regardless of how many times it is re-rendered. A React functional component using hooks is called whenever a re-render occurs as a result of a state/prop change, which pressures the browser's garbage collector. React provides useCallback to prevent inline functions in functional components from being garbage collected on subsequent re-renders via a referential equality check. Additionally, these re-renders may cause unnecessary re-renders, which happens when the function representing a child functional component is called when its parent component is re-rendered, even if it is completely stateless. Example : When the count increases/decreases upon clicking any one of the <Counter /> component's button, the Child function is called. However, its DOM is unaffected by this state change. This is an unnecessary re-render. If this component was larger with more inline handlers, calls to hooks, etc., then any unnecessary re-render would cause these inline handlers, etc. to be garbage collected. React provides a number of memoization-related methods ( useMemo , memo , etc.) to address this. Of course, you should use your browser's profiling tool first to identify your application's actual bottlenecks before chucking in useMemo , memo and other memoization techniques. Each developer reasons about code differently. Whether you find it easier to reason about code by its low-level (Options API, which is better suited for grouping logic by a low-level attributes of a component) or high-level (Composition API, which is better suited for grouping logic by a component's high-level features) implementation, you must always evaluate and make trade-offs that best serves your needs. You should definitely read this RFC that outlines the Vue team's rationale and decisions for the Composition API, along with addressing some of the common criticisms echoed within the Vue community. Many of these new features, such as portals and fragments, in Vue 3 are already present in React v16+. Try converting your React functional components to Vue 3 components using the Composition API. Please read Part 2 of this blog post to learn about the main benefit of the Composition API: the capability to extract and reuse shared logic . If you want to learn more about Vue 3, then check out Fullstack Vue :

Thumbnail Image of Tutorial Vue 3 - The Composition API (Part 1)

Svelte Lifecycle Method - beforeUpdate

In Svelte, a component's beforeUpdate lifecycle method is called before the component is updated as a result of a state change. When the component receives new prop values or has its local state modified, the component's beforeUpdate lifecycle method is called before any updates to the DOM are made. Once the beforeUpdate lifecycle method finishes executing, the DOM will be updated with these data changes, which will allow the subsequent call to afterUpdate to have access to a completely synced DOM. Being able to schedule a callback to run at this phase of a component's lifecycle ensures that the value of certain DOM properties, such as a container element's scrollTop , can be cached prior to being updated. Then, these cached values can be used to revert those properties back to what they were originally. Here's a template of how the beforeUpdate lifecycle method is used inside of a component: Note : beforeUpdate is called before the component's initial onMount . Below, I'm going to show you: Suppose you are formatting text within an editable element, such as an <input /> or <textarea /> via a set of controls in a floating tooltip. When you create a selection by dragging your cursor over a subset of the text and click on any one of the tooltip options to transform the text, the selected text should be modified with the selection and focus on the editable element still intact. By default, clicking anywhere outside of an editable element will cause it to lose its focus and current text selection. This does not happen when clicking on any of the buttons in the tooltip because of additional code that preserves the selection and focus. Visit this simple Svelte REPL demo to see how both the focus and text selection can be immediately restored using the beforeUpdate lifecycle method: Demo - beforeUpdate Lifecycle Method - Restore Input Cursor Position In this demo, there are four buttons, each of which transform the input field's text selection differently: When any one of these buttons is clicked while there is a text selection in the input field, the transformText function is called. This function transforms the text selection and sets value to the newly transformed text. Because value is updated with a new value, the beforeUpdate lifecycle method will be called, which checks if input exists (since beforeUpdate is called before the component is mounted) and caches the start and end positions of the text selection. After the DOM is updated and the new value is rendered within the input field, the afterUpdate lifecycle method will be called, which will recreate the text selection based on the cached positions and place the focus back on the input field. If you have built React applications, then you will have probably noticed how beforeUpdate can be used similarly to getDerivedStateFromProps / shouldComponentUpdate / getSnapshotBeforeUpdate . Try rewriting some of the those components that use getDerivedStateFromProps / shouldComponentUpdate / getSnapshotBeforeUpdate as Svelte components that use beforeUpdate . Because beforeUpdate is often used in tandem with afterUpdate , check out the afterUpdate blog post for more examples using beforeUpdate . If you want to learn more about Svelte, then check out Fullstack Svelte :

Thumbnail Image of Tutorial Svelte Lifecycle Method - beforeUpdate

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

Svelte Lifecycle Method - onMount

In Svelte, a component's onMount lifecycle method is called after the first time the component has been rendered to the DOM. For example, if you have a component that is wrapped within an {# if} block, then when this block's conditional statement is fulfilled, the component will be mounted to the DOM, at which point onMount will be called. Being able to schedule a callback to run at this phase of a component's lifecycle ensures that DOM elements within the component will be available for your code to access/manipulate. Here's a template of how the onMount lifecycle method is used inside of a component: Considered the most commonly used lifecycle method, onMount covers a wide diversity of use cases such as... Below, I'm going to show you: When you visit the G-Mail login page, you will notice that the e-mail address input field is automatically focused: This convenience automates away the initial click (or tabbing) into the input field that the user would have to do before being able to type in their e-mail address. Using the onMount lifecycle method, the focus can be moved to an input field when the component is initially rendered. Visit this simple Svelte REPL demo to see how to automatically focus an input field using the onMount lifecycle method: Demo - onMount Lifecycle Method - Login Form When you load the Svelte REPL, the e-mail address input field is automatically focused (indicated by its blue outline). The bind:this directive sets the variable it's passed a reference to an element's DOM node. Here, the emailAddressInput variable is set to the <input type="email" /> element. Since onMount runs after the component has been rendered, the input field will exist by the time this method is executed. Therefore, emailAddressInput will have been set to this input field, and the focus can immediately be moved to it. Note : Automatically focusing into an input field may skip over vital information a user using assistive technologies should be aware of. This may have negative implications on the accessibility of the application. Lazy-loading content reduces the initial load time of an application and reduces bandwidth by delivering only what the client has requested. Imagine having to wait seconds or minutes for a large webpage containing tables with thousands or millions of rows to be downloaded before seeing any content in your browser. Before the webpage finishes downloading, you would have most likely moved on to a different webpage. Wouldn't it be better if you were presented some content immediately (to keep you engaged), and then be shown a "loading" message when you request to view a large table? The onMount lifecycle method can be used to retrieve data from a remote API. This data can then be set to a variable in your component, which will cause the component to only re-render the part of the DOM that's affected by changes to this variable. This is especially useful for lazy-loading a table that contains many records. Visit this simple Svelte REPL demo to see how to fetch motor vehicle collisions data from the NYC Open Data API and render this data as rows of cells in a table using the onMount lifecycle method: Demo - onMount Lifecycle Method - NYC Open Data API Here, we are fetching data from the NYC Open Data Portal, particularly on NYC motor vehicle collisions . Each record of this dataset features the location of the accident, the vehicles involved, the number of fatalities, etc. For fetching data, we are using the native fetch method. The fetch method returns a Promise , so we will schedule an async callback to run when the component is mounted. While the data is being fetched, a "Loading..." message is presented to the user to notify them of the table's status (initially, isLoading is set to true , and this flag toggles this message on/off). Once the data is downloaded and parsed, the collisions variable is set to this data and the isLoading flag is set to false. As a result, the "Loading..." message disappears, and a select number of features of each record are displayed in the table. Note : Alternatively, this can be accomplished with an {#await } block ! Note : Since onMount is not ran during server-side rendering, if you need to fetch data within a component after its initial rendering, then it must be done within onMount and not outside at the top-level of <script /> . Note : Since async functions always return a Promise , onMount cannot return an unmount function since it must synchronously return a value. Event listeners execute code when an event, such as moving the mouse, takes place on the element it's binded to. In component-based applications, event listeners are registered once the component has been rendered to the page. Visit this simple Svelte REPL demo to see how to add an event listener on the window "resize" event using the onMount lifecycle method: Demo - onMount Lifecycle Method - Window Resize As you resize the browser window, notice how the window width displayed in the view changes. Just before the component is unmounted from the DOM, the unmount callback returned from onMount will be executed. This will remove this event listener from window , which will avoid memory leaks in legacy browsers, such as Internet Explorer, that do not automatically garbage-collect event handlers of removed DOM elements. When embedding a widget/plugin from a third-party library, those libraries will need to know where to place the widget/plugin in your application. For example, to display Google Maps via Google's Maps JavaScript API , the first argument to the google.maps.Map method is a reference to an existing DOM element (often document.getElementById('map') ) on the page where you wish to place the map. Visit this simple Svelte REPL demo to see how to embed a Leaflet map into your Svelte application using the onMount lifecycle method: Demo - onMount Lifecycle Method - Leaflet Map The <svelte:head /> element inserts elements into the <head /> element of the document. In this context, we are adding the Leaflet CSS and JavaScript files. By using <svelte:head /> , it keeps all Leaflet-related code encapsulated within a single component that contains all code related to rendering the Leaflet map. When the component is mounted, the <div id="map" /> container element will exist when the onMount callback is executed. The Leaflet library will be able to find this element and initialize the map. Note : This can also be done with Google Maps, but this example uses Leaflet since the Google Maps API requires an API key. To generate this API key, you must provide Google with your billing information in their Google Cloud Platform, and I felt this would add more an unnecessary obstacle to learning how load an embeddable widget/plugin with onMount . Note : If the Leaflet map is toggled on/off, then return an unmount callback that runs map.remove() to destroy the map and clear all of its related event listeners. Let's take the focus input example and refactor it. Instead of having the onMount code (and its contents) in the same file as the component, let's move it into an external module. Demo - onMount - External Module ( onMount.js ) ( App.svelte ) Notice how the bind:this directive was removed from the e-mail address input field. This is because the reference of the DOM node captured by this directive cannot be passed as an argument to the onMountFocusInput method. The DOM node reference will not be available when this method is executed since it is called at the top-level of the <script /> tag. Instead, we can pass an id value so that onMount can query for the input field element once the component that contains it is rendered. Additionally, by moving this onMount code outside of the component, it can be reused for other components that may need to automatically focus an input field when they are rendered to the page. If you have built React applications, then you will have probably noticed how similar onMount is to componentDidMount / useEffect . Try rewriting some of the those components that use componentDidMount / useEffect as Svelte components that use onMount . If you want to learn more about Svelte, then check out Fullstack Svelte :

Thumbnail Image of Tutorial Svelte Lifecycle Method - onMount

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

Svelte Lifecycle Method - afterUpdate

In Svelte, a component's afterUpdate lifecycle method is called after the component is updated as a result of a state change. When the value of any of a component's props and variables changes, the component's beforeUpdate lifecycle method is executed prior to any DOM updates being made in response to these changes. Once the beforeUpdate lifecycle method is finished running, the DOM is updated to reflect the data changes. After completing this update, the afterUpdate lifecycle method is executed. Being able to schedule a callback to run at this phase of a component's lifecycle ensures that the DOM is completely updated and synced with any new state and prop values. Here's a template of how the afterUpdate lifecycle method is used inside of a component: When using the afterUpdate lifecycle method, remember that it runs on every state and prop change. For components that experience many state and prop changes, it can be quite cumbersome to track which variables/props have changed in order to then execute the appropriate code. This is unlike React's componentDidUpdate lifecycle method , which provides the previous props and state as arguments. Below, I'm going to show you: The Markdown syntax formats plain text into structured content that can be published to the web as valid HTML markup. Commonly, developers write API documentation and blog posts using Markdown. To avoid typos and inconsistencies while writing Markdown, tools and editors have been built to instantly live preview the rendered output of Markdown content. Visit this simple Svelte REPL demo to see how to live preview Markdown using the markdown-it Markdown parser library and the afterUpdate lifecycle method: Demo - afterUpdate Lifecycle Method - Markdown Editor Here, we have a <textarea /> element on the left for writing Markdown and a <div /> container element on the right for rendering the output of the Markdown. markdown-it provides a render method that accepts Markdown as an argument and returns the generated HTML as a string. This HTML string can be rendered as HTML using the @html template syntax . Anytime an HTML string is rendered via the @html template syntax, the HTML string should be sanitized (before rendering) to prevent cross-site scripting, especially if the original source is untrusted. Pass the result of md.render as an argument to the sanitizeHtml function of the sanitize-html library to remove malicious HTML code. Changes to the value of markdown (bound to the <textarea /> element via the bind:value directive) will trigger the afterUpdate lifecycle method, which will take this value and convert it to stringified HTML that is sanitized. This result will be rendered as HTML. As you type Markdown into the <textarea /> , the output of the Markdown will be displayed and live updated, giving you immediate feedback on your Markdown. Note : Alternatively, this same behavior can be achieved by using a reactive statement. Many websites provide a theme toggle to dynamically change their appearance based on a user's color preferences. To implement theming, use CSS variables and change the value of those variables whenever a different theme is selected. Visit this simple Svelte REPL demo to see how to toggle themes using the afterUpdate lifecycle method: Demo - afterUpdate Lifecycle Method - Theme Toggle Using a <div /> element with a class body to serve as a pseudo <body /> element, it has a background-color CSS property set to var(--background-color) and a color CSS property set to var(--color) . These theme values are pre-defined in an object themes , and whenever any of these two buttons are clicked, the toggle function is called, and the theme variable is set to either themes.dark or themes.light (depending on the button clicked). When theme is updated, the afterUpdate lifecycle method is called, and the values of the CSS variables are updated accordingly. Note : Without label in the theme object, the afterUpdate lifecycle method would not be called because the theme object would not referenced anywhere in the HTML markup of the component. Note : Alternatively, this same behavior can be achieved by using a reactive statement. From top to bottom, chat clients display messages in ascending order of their timestamp, with the oldest messages at the top and the most recent messages at the bottom adjacent to the "Send Message" input field. When a new message is received within a chat client, the user is automatically scrolled to that message at the bottom of the scrollable view, assuming that they haven't scrolled beyond a certain threshold that indicates the user browsing through older messages. Visit this simple Svelte REPL demo to see how chat clients auto-adjust a user's scroll position upon receiving a new message using the afterUpdate lifecycle method: Demo - afterUpdate Lifecycle Method - Auto-Adjust Scroll Position in Messaging Client ( ChatClient.svelte ) In this demo, there are two chat clients, one for a user named "Jesse" and another for a user named "Alex." Whenever any one of these two users sends a message, the message will be displayed in both clients since these messages are based on a conversation between these two users. Messages sent by the user are styled with a blue background and white text, while messages received by the user are styled with a light-grey background and black text. The <ChatClient /> retrieves these messages from a store: When the user submits a new message, the addMessage method will be called to concatenate a new message to the messages array, and the input field where the user types messages will be cleared. Because the messages array is modified (and is used to render messages), the beforeUpdate and afterUpdate lifecycle methods are called. beforeUpdate is called to determine whether or not to automatically scroll the user to the bottom of the <div /> container element (reference stored in messagesContainer ) to see the new message. If the user is within 20px of the bottom-most scroll position of this container element, then the shouldAutoScroll flag will be set to true , and the client will automatically scroll to the bottom of this container element so that the user can see the latest received message. This must be done before the DOM is updated with the new message because adding a new message will increase the scrollHeight by more than the 20px threshold (due a message's minimum height), and thus, cause the calculation to keep assuming that you are browsing through older messages even though you are not. Once the DOM is updated with the new message, the afterUpdate lifecycle method will be called, and it will scroll to the bottom of the container depending on the value of the shouldAutoScroll flag. To animate an element, the element must sequentially transition from a starting state to an ending state. For example, you may want to move a square from the top-left corner (starting state) of a view to the bottom-right corner (ending state) of a view. In between these two states, there may be intermediate states that the element must fulfill. For example, maybe you want the square to move in a zig-zag motion towards the bottom-right corner rather than in a straight diagonal motion. Additionally, parameters such as duration , timing function and delay must be factored into each step. Referring back to the square example, each step in the animation requires knowing the most recent (x, y) coordinates of the square's position and the (x, y) coordinates of the square's next position in the zig-zag motion. And this continues on for each adjacent pair of steps in the animation sequence. At each step, you would cache the current coordinates of the square and calculate the difference between these coordinates and the next coordinates of the square. Using the calculated displacement (and other parameters like the ones mentioned previously), the square can be animated from point A to point B. In Svelte, animating an element can be done using the beforeUpdate and afterUpdate lifecycle methods. The below snippet of code is based on a demo presented at Svelte Summit 2020: In the beforeUpdate lifecycle method, before each DOM update, the current coordinates ( x and y ) of the animating element ( node ) are cached. In the afterUpdate lifecycle method, after each DOM update, the cached coordinates are subtracted from the current coordinates to determine how far away these coordinates are from one another ( dx and dy ). Then, either a spring-based (via createSpringAnimation ) or keyframe (via createKeyframes ) animation is performed (via node.animate ) using these calculated differences ( keyframeFn({ dx, dy }) ). Visit this Svelte REPL demo to see this in action: Demo - afterUpdate Lifecycle Method - Custom Svelte Action - Shuffle Animation Note : This demo is based on the Svelte Summit 2020 demo. In this demo, pressing the "Shuffle" button randomly rearranges the cat pictures in a two column masonry grid layout (columns are 300px in width). The pictures are smoothly translated from one slot to another. Each picture <div /> element is attached element-level lifecycle methods via a Svelte action ( translate.action , prefixed with the use directive). These methods are called when the element is created, destroyed, etc. Here, translate.action is assigned the translateElement function, which contains the exact same code as previously mentioned with the beforeUpdate and afterUpdate lifecycle methods. ( translate.js ) If you continuously press the "Shuffle" button, then the pictures will be shuffled around until the "Shuffle" button is no longer pressed, at which point, the pictures will be able to animate to their designated new slots. This "shuffling around" behavior is made possible by the following code that uses the afterUpdate lifecycle method. The tick function is called ensure that all pending state changes have been reflected to the DOM. Then, translate.flush executes all of the animation steps queued via the syncLayout.read and syncLayout.write methods in the translateElement function. This allows the translation animation to be ran smoothly irregardless of interruptions. If this block of code was commented out, then the pictures would "blink" immediately to their designated new slots. Note : Alternatively, you can use one of Svelte's built-in animation directives such as flip . If you have built React applications, then you will have probably noticed how similar afterUpdate is to componentDidUpdate / useEffect . Try rewriting some of the those components that use componentDidUpdate / useEffect as Svelte components that use afterUpdate . If you want to learn more about Svelte, then check out Fullstack Svelte :

Thumbnail Image of Tutorial Svelte Lifecycle Method - afterUpdate

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