Synchronous vs. Asynchronous in connectedCallback()
and @wire
Feature | connectedCallback() | @wire |
---|---|---|
Execution Type | Synchronous | Asynchronous |
When It Runs | Runs immediately when the component is inserted into the DOM. | Runs asynchronously after the component is initialized. |
Data Fetching | Calls Apex methods imperatively, meaning it executes the function and waits for the result (Promise-based). | Uses reactive data fetching, meaning data is retrieved asynchronously and updates the UI automatically when data changes. |
Blocking or Non-Blocking? | Blocking – It executes sequentially until it completes. | Non-blocking – Data is fetched in the background and updates the component when available. |
connectedCallback()
is Synchronous
- The function inside
connectedCallback()
executes immediately when the component is inserted into the DOM. - However, if it contains an asynchronous operation (like an Apex call), the function itself is synchronous, but the Apex call is asynchronous.
⚡ Example: Synchronous Execution in connectedCallback()
🔄 Example: Making an Asynchronous Apex Call in connectedCallback()
🔹 The Apex call (getAccounts()
) is asynchronous, but connectedCallback()
itself is synchronous.
@wire
is Asynchronous
- The
@wire
decorator runs asynchronously in the background and updates the component when the data is available. - It does not block the component from rendering.
Example: Asynchronous Execution in @wire
🔹 The console log runs first, and the data arrives asynchronously.
Key Takeaways
Feature | connectedCallback() | @wire |
---|---|---|
Execution | Synchronous (but can contain asynchronous calls) | Asynchronous |
Data Fetching | Manual, imperative (Apex call returns a Promise) | Automatic, reactive |
Blocking UI? | Can block UI if used incorrectly | Non-blocking (fetches in the background) |
When to Use | External API calls, event listeners, manual control | Salesforce data fetching, automatic updates |
Conclusion:
@wire
is better for handling Salesforce data reactively.connectedCallback()
is better for initializing the component, subscribing to events, or calling external services.
No comments:
Post a Comment