<commit_before># Lifecycle methods

- [Usage](#usage)
- [The DOM element lifecycle](#the-dom-element-lifecycle)
- [oninit](#oninit)
- [oncreate](#oncreate)
- [onupdate](#onupdate)
- [onbeforeremove](#onbeforeremove)
- [onremove](#onremove)
- [onbeforeupdate](#onbeforeupdate)
- [Avoid anti-patterns](#avoid-anti-patterns)

---

### Usage

[Components](components.md) and [virtual DOM nodes](vnodes.md) and can have lifecycle methods, also known as *hooks*, which are called at various points during the lifetime of a DOM element.

```javascript
// Sample hook in component
var ComponentWithHook = {
	oninit: function(vnode) {
		console.log("initialize component")
	},
	view: function() {
		return "hello"
	}
}

// Sample hook in vnode
function initializeVnode() {
	console.log("initialize vnode")
}

m(ComponentWithHook, {oninit: initializeVnode})
```

All lifecyle methods receive the vnode as their first arguments, and have their `this` keyword bound to `vnode.state`.

Lifecycle methods are only called as a side effect of a [`m.render()`](render.md) call. They are not called if the DOM is modified outside of Mithril.

---<commit_msg>Update lifecycle-methods.md<commit_after># Lifecycle methods

- [Usage](#usage)
- [The DOM element lifecycle](#the-dom-element-lifecycle)
- [oninit](#oninit)
- [oncreate](#oncreate)
- [onupdate](#onupdate)
- [onbeforeremove](#onbeforeremove)
- [onremove](#onremove)
- [onbeforeupdate](#onbeforeupdate)
- [Avoid anti-patterns](#avoid-anti-patterns)

---

### Usage

[Components](components.md) and [virtual DOM nodes](vnodes.md) can have lifecycle methods, also known as *hooks*, which are called at various points during the lifetime of a DOM element.

```javascript
// Sample hook in component
var ComponentWithHook = {
	oninit: function(vnode) {
		console.log("initialize component")
	},
	view: function() {
		return "hello"
	}
}

// Sample hook in vnode
function initializeVnode() {
	console.log("initialize vnode")
}

m(ComponentWithHook, {oninit: initializeVnode})
```

All lifecyle methods receive the vnode as their first arguments, and have their `this` keyword bound to `vnode.state`.

Lifecycle methods are only called as a side effect of a [`m.render()`](render.md) call. They are not called if the DOM is modified outside of Mithril.

---
{'fraction_non_alphanumeric': 0.13449781659388646, 'fraction_numerical': 0.0, 'mean_word_length': 4.950649350649351, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1649678', 'n_tokens_mistral': 742, 'n_tokens_neox': 697, 'n_words': 226}