hooks
included in @reatom/framework
All atoms and actions have a hooks to they lifecycle, this package exposes friendly helpers to use this hooks.
We assumes that you already read lifecycle guide.
A lot of cool examples you could find in async package docs.
onConnect
#onConnect
allows you to react to atom connection (first subscribtion). Optionally, you could return a cleanup callback.
All connection (and disconnection) callbacks calling during effects queue - outside batching. The returned value is a dispose function used to deactivate the hook.
”Connection” refers to the presence of any number of subscribers in the atom. The first subscriber activates the connection status, while the second subscriber does not interact with it. Unsubscribing the first subscriber has no effect since there is still one subscriber (the second one). However, after unsubscribing the second subscriber, the connection status will be deactivated, and if a cleanup callback is provided, it will be triggered. You can read more in the lifecycle guide.
The passed ctx
has an isConnected
method to check the current status of the passed atom. You can refer to the async example for more information. Additionally, the ctx
includes a controller
property, which is an AbortController. You can conveniently reuse it with reatomAsync
. For further details, you can refer to another async example.
Comparison with React
#For example, in React you should manage abort strategy by yourself by useEffect
, if you want to cancel async process on unmount.
With Reatom, you can simplify it and make it more readable.
Isn’t it cool, how the size of the code is reduced and how the logic is simplified?
onDisconnect
#Shortcut to onConnect
returned callback.
withInit
#This operator helps you to initialize the state lazily on the first atom read.
You can use it to depend the init state from an other atom too.
Also, you can use it to do a side effects in rare cases.
Note that the subscription will leave forever. To manage resources more efficiently, you can use should use probably onConnect.
isInit
#This utility allows you to check that the current atom or action is being called for the first time (in the current context). It is useful to perform some initialisation effects only once.
onUpdate
#The onUpdate
hook allows you to react to state updates of the passed atom. However, this hook will be deprecated in the future. It is recommended and more convenient to use the atom’s onChange
method and the action’s onCall
method. You can find more information about these methods in the core package documentation.
For general computed atoms (via ctx.spy
), it is only called when the atom is connected. You can read more in the lifecycle guide.
One unique feature of onUpdate
is that it could activate the entire chain of dependent atoms if they are LensAtom
or LensAction
from the lens package. It useful when you want to delay or sample the reaction.