Template Lifecycles

Markup templates offer a convenient way to tap into its lifecycles, so you can perform setup and teardown actions.

onMount

The onMount lifecycle allows you to react to when the template is rendered. This is triggered whenever the render and replace methods successfully render the nodes in the provided target.

const temp = html`
  <p>sample</p>
`;

temp.onMount(() => {
  // handle mount
})

temp.render(document.body)

You can always check if the place the template was rendered is in the DOM by checking the isConnected on the renderTarget.

temp.renderTarget.isConnected;

onUnmount

The onUnmount lifecycle allows you to react to when the template is removed from the element it was rendered. This is triggered whenever the unmount method successfully unmounts the template.

const temp = html`
  <p>sample</p>
`;

temp.onUnmount(() => {
  // handle unmount
})

temp.render(document.body)

You can call the unmount method directly in the code but Markup also tracks templates behind the scenes individually.

Whenever templates are no longer needed, the unmount method is called to remove them. Thus, all the cleanup for the template is performed.

onUpdate

The onUpdate lifecycle allows you to react to when an update is requested for the template. This can be by calling the update method or automatically is you are using state.

const [count, setCount] = state(0);

const temp = html`
  <p>${count}</p>
`;

temp.onUpdate(() => {
  // handle update
})

temp.render(document.body)

Chainable methods

Markup allows you to chain the following methods: render, replace, onMount, onUnmount, and onUpdate.

html`<p>sample</p>`
 .onMount(() => {
   // handle mount
 })
 .onUnmount(() => {
   // handle unmount
 })
 .onUpdate(() => {
   // handle update
 })
 .render(document.body)

This makes it easy to handle things in a function where you need to return the template.

const Button = ({content, type, disabled}) => {
  
  return html`
    <button
      type="${type}"
      disabled="${disabled}"
    >
      ${content}
    </button>
  `
     .onUpdate(() => {
       // handle update
     })
}