[SalesForce] When do @wire methods run (LWC)

General question about Lightning Web Components: if I define a wired javascript method (in this case wired to an apex method), when does it run? And when does it run initially?

Here's what the docs have to say here https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.apex:

Marking a method as cacheable improves your component’s performance by quickly showing cached data from client-side storage without waiting for a server trip. If the cached data is stale, the framework retrieves the latest data from the server…

..The caching refresh time is the duration in seconds before an entry is refreshed in storage. The refresh time is automatically configured in Lightning Experience and the Salesforce mobile app.

So my understanding is that after the initial time the method runs, it will rerun whenever the cache is "stale", either because the framework decides it is, or we call the refresh method. But what about the initial run? Do wired methods always run when the page loads? Because the cache is empty at that point?>

I expected they would run when called or referenced, but we created one that was neither referenced nor called and it was running on load anyway. Want to make sure that's the expected behavior.


If it is, then my further question is: what to do when you have a hierarchical component arrangement and you want one of the inner components to be able to refresh itself, but want the initial data load to happen at a higher level? Seems we can't wire the component's query because then it'll run on load, which we don't want since it'll generate a ton of queries. Right now we're using a non-cacheable apex method for the inner component refresh, and calling it imperatively — this works, but seems inelegant.

That question is abstract, but hope it makes sense. If not, I can try to provide more detail.

Best Answer

You have two different questions here, but I will try to answer this one:

But what about the initial run? Do wired methods always run when the page loads?

That is correct. I myself was trying to identify as when does the wired method get invoked. And based on a test I came to the conclusion that it always gets invoked the time the component is being created.

However the methods need to be annotated with @AuraEnabled(cacheable=true), because if not, then you will need to invoke it imperatively.

I have a small test around this topic and its results here.


As for your other question on hierarchical components, if you want to the queries to be fired on demand, then its better to go the imperative approach.