Lifecycle Methods

by mithril

Level: intermediate • Mithril.js Version: latest

Here we have an example showing all lifecycle methods from Mithril.js. This is very useful for seeing how things work and in what order. The example was taken from the official website at and slightly modified.

Live Example


Type Name URL


var ComponentWithHooks = {
    oninit: function(vnode) {
    oncreate: function(vnode) {
        console.log("DOM created")
    onbeforeupdate: function(newVnode, oldVnode) {
        return true
    onupdate: function(vnode) {
        console.log("DOM updated")
    onbeforeremove: function(vnode) {
        console.log("exit animation can start")
        return new Promise(function(resolve) {
            // call after animation completes
    onremove: function(vnode) {
        console.log("removing DOM element")
    view: function(vnode) {
        return "hello"

function initialize(vnode) {
  console.log("initialized as vnode")

m.mount(document.body, {
  view: () => m(ComponentWithHooks, {oninit: initialize})

The snippet is using the most current version of Mithril.js framework. It is aimed at intermediate users who are familiar with most of the aspects of the framework.

In addition to the Mithril.js hyperscript function m(), here we can see an example of Mithril.js' m.mount API method. It also shows, how Mithril.js' hooks (called lifecycle methods) like onbeforeupdate, onremove, onbeforeremove, onupdate, oncreate and oninit can be used. In this example we can also see the usecase of Vnodes (virtual DOM nodes) which is a JavaScript data structure that describes a DOM tree.

The example was contributed by mithril and last modified on 19 October 2021. Click here to see more examples contributed by the author.


If anyone has some improvements, that should be addressed, let me know by opening an issue. Or simply fork the repository on GitHub, push your commits and send a pull request. For starting your work, you can click the edit link below. Thanks for contributing.

See more code examples  •  Edit this example on GitHub