useAtom
Accessing state, mutating state
In most real world scenarios you'll not want to constantly re-define all of your functions and event handlers. The performance impact would be too high. However, useState lacks an important feature that would help you to avoid all of complexity: an accessor function.
Thus, it is strongly advisable to rely on useAtom instead. It still offers a similar level of convenience and hides the complexity very nicely but it allows you to avoid the most common mistakes when it comes to state handling in Melody.
Signature
useAtom(initialValue): [accessorFunction, mutatorFunction, currentValue]
The useAtom hook returns an accessorFunction, which returns the current value at any given time, a mutator function which allows to modify the value and the current value stored in it.

As a rule of thumb, you should use the accessor function in anything related to event handling while the current value is most useful when you intend to pass data to the template or you wish to ensure a side effect is being run whenever the value changes.
Example
Let's build the prime example of a counter that has to be in a selected state in order for the user to be able to increase or decrease it again.
Without the useAtom hook, we'd have to constantly re-define our event handlers, adding a lot of noise around adding and removing event handlers. Thus, it is strongly recommended to prefer useAtom over useState.
Implementation
Last updated
Was this helpful?