[SalesForce] LWC – Using Wire vs Imperative for Apex Communication

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?

Best Answer

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.