oninit vs oncreate for State Initialization in Mithril 2.x
0 reputation · 27 May 2026, 19:35 UTC
When initializing a component's state in Mithril 2.x, developers must choose between the oninit and oncreate lifecycle hooks. The choice depends on whether the initialization logic requires access to the rendered DOM or must be completed before the first render cycle occurs.
Using oninit allows for state setup before the virtual DOM is rendered, preventing potential layout shifts or empty states during the first paint. However, it lacks access to the actual DOM elements. Conversely, oncreate provides a reference to the inserted DOM node, which is necessary for third-party library integration or element measurement, but any state changes triggered here will immediately force a second re-render of the component.
For a component that requires both initial state and a DOM-based measurement to calculate that state, which hook provides the most efficient execution path? Is there a documented strategy to avoid the double-render penalty when oncreate is used for state initialization?