4

I started writing LWCs, does anyone have an opinion on when to use @wire vs calling it imperatively?

Given that it appears that you can set cacheable for both, but due to the requirement for this with @wire, you can't do dml through @wire. It seems like imperatively you can do everything you want and its simpler to just use a single method to call apex.

What am I missing? Outside of saving a couple lines of code when you're sure the apex class will return what you need, whats the value in using @wire?

9

Wire methods take care of the entire life cycle of an attribute when it changes, including fetching calling the method, updating the attribute, and and refreshing the UI, all in often a single line of code (or just a few for custom error handling). While you could do all this imperatively, it would require significant amounts of code. In other words, yes, wire methods are basically just a "shortcut" for calling Apex imperatively, but you should not discount those savings, which could easily be hundreds of lines of code in a large component. Also, specifically, the wired method approach means you don't need to write custom setters to make sure the method is called every time the attribute is updated, or remember to call the method imperatively every time. This centralizes calling the method to a single location, making it much less likely you'll forget to call the method when appropriate.

1

I have found @wire is especially useful when you want to get a single or list of records without modifying any of the return values.

Think of using force:hasRecordId and using LDS for example, you can do this with less code with @wire now.

LWC docs use of recordId

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.