Lifecycle methods
There are a few lifecycle methods that can be useful.
:ruby
def self.get_initial_state(**) = {
count: 0
}
def mount
loop do
sleep 1
update do |state|
{ count: state[:count] + 1 }
end
end
end
%span Count: #{state[:count]}
List of lifecycle methods
def self.get_initial_state(**props)
Called when initializing the component.
It has to return a Hash with the initial state.
def mount
Called when the component gets mounted.
This is a good place to start async task or periodic updates. All tasks will be stopped when the component unmounts.
:ruby
def mount
loop do
update(time: Time.now.to_s)
sleep 1
end
end
%p= state[:time]
This component will update the current time every second.
def unmount
Called after the component has been unmounted.
def should_update?(next_props, next_state)
By default, components will re-render on every change, but in some cases you might want to skip rendering to improve performance.
Usually you don’t need to override the default behavior.
Should return true
or false
.
def did_update(prev_props, prev_state)
The did_update
method is called right
after a component has been updated.
def self.get_derived_state_from_props(props, state)
Should return nil
or new state.