Lifecycle #
Basics #
The render()
method of a component will be called the first time the component is
mounted to the DOM. This is generally speaking a good place to declare component local
state. There are cases where you might need to run code after the component is done
rendering (code you write in the render method will run just before rendering) or when
it is unmounted. For these and other situations, Mvui provides two lifecycle hooks:
this.onAdded(<callback>)
will run the callback on every mount (if its the first mount, it will run before rendering)this.onRemoved(<callback>)
will run the callback on unmountthis.onRendered(<callback>)
will run the callback after the component is rendered. Recall that components in Mvui will only render once when first mounted and subsequent state changes will only update the relevant DOM.
Callbacks added withonRemoved
,onRendered
andonAdded
can be removed with theremoveLifecycleHook
. You won’t have to do this very often since these callbacks should be cleaned up by garbage collection when the component in question is no longer referenced anywhere.
Closing Local Resources (e.g. Subscriptions) #
You can use this.subscribe(<callback>)
to subscribe to a Stream
(we will talk those
later in the chapter on
reactivity
) only when the
component is mounted. While you generally speaking should try to avoid manual
subscriptions for a more declarative style, there are some use cases where they may be
required (or desirable for your sanity as a non-expert in reactive programming).