Difference Between @wire and Imperative Way of Calling Apex Class in LWC

Difference Between @wire and Imperative Way of Calling Apex Class in LWC
Chinmaya By Chinmaya
5 Min Read

Introduction

In Salesforce Lightning Web Components (LWC), interacting with server-side Apex logic is essential for building dynamic, data-driven applications.

Two primary methods exist for calling Apex classes:

    1. @wire (Reactive)
    2. Imperative Approach

Each serves different use cases and has unique strengths.
This post provides a comprehensive comparison to help you decide which to use in various scenarios.

Overview of @wire and Imperative Apex

1. Reactive (@wire)

The @wire decorator in LWC is used to call an Apex method reactively.

It automatically invokes the Apex method when the component is loaded or when dependent parameters change.

In case of @wire decorator, there is no user interference required to call the apex class.

2. Imperative

In the imperative approach, Apex methods are called programmatically, often in response to user actions like button clicks or dynamic events.

This approach gives you full control over the execution timing.

In case of Imperative approach, the apex method is not called automatically.

Key Differences Between @wire and Imperative Apex

Aspect @wire (Reactive) Imperative

Execution Control

Automatically triggers based on parameters or lifecycle.
Manually invoked in response to user actions.

Syntax

Uses the @wire decorator.
Calls Apex methods like a JavaScript function.

Use Case

Ideal for automatically fetching data when components render or parameters update.
Best for user-driven actions like button clicks.

Error Handling

Errors are accessed via error property of the @wire.
Explicit handling with try-catch or .catch().

Data Refresh

Automatically refreshes when dependent parameters change.
Must be re-invoked manually to fetch updated data.

Dynamic Parameters

Supports reactivity based on parameter changes.
Requires dynamic parameters to be passed explicitly.

Flexibility

Limited flexibility; dependent on the @wire lifecycle.
High flexibility; executed whenever needed.

UI Blocking

Non-blocking (async).
Non-blocking (async).

Governor Limits

Automatically optimized.
Manually optimized by the developer.

Practical Example 1: Fetching Data with @wire

This example demonstrates fetching a list of accounts when the component loads.

Apex Class:

				
					public with sharing class AccountController {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccounts() {
        return [SELECT Id, Name, Industry FROM Account LIMIT 10];
    }
}
				
			

JavaScript File

				
					import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';

export default class WireExample extends LightningElement {
    @wire(getAccounts)
    accounts;

    get hasAccounts() {
        return this.accounts?.data?.length > 0;
    }
}
				
			

HTML File

				
					<template>
    <template if:true={hasAccounts}>
        <ul>
            <template for:each={accounts.data} for:item="account">
                <li key={account.Id}>{account.Name} - {account.Industry}</li>
            </template>
        </ul>
    </template>
    <template if:true={accounts.error}>
        <p style="color:red;">Error: {accounts.error.message}</p>
    </template>
</template>
				
			

Practical Example 2: Fetching Data with Imperative Apex

Apex Class:

				
					public with sharing class AccountController {
    @AuraEnabled
    public static List<Account> getAccounts() {
        return [SELECT Id, Name, Industry FROM Account LIMIT 10];
    }
}
				
			

LWC JavaScript:

				
					import { LightningElement, track } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';

export default class ImperativeExample extends LightningElement {
    @track accounts;
    @track error;

    fetchAccounts() {
        getAccounts()
            .then((result) => {
                this.accounts = result;
                this.error = undefined;
            })
            .catch((error) => {
                this.error = error.body.message;
                this.accounts = undefined;
            });
    }
}
				
			

LWC HTML

				
					<template>
    <lightning-button label="Fetch Accounts" onclick={fetchAccounts}></lightning-button>
    <template if:true={accounts}>
        <ul>
            <template for:each={accounts} for:item="account">
                <li key={account.Id}>{account.Name} - {account.Industry}</li>
            </template>
        </ul>
    </template>
    <template if:true={error}>
        <p style="color:red;">Error: {error}</p>
    </template>
</template>
				
			

When to Use Each Approach

Use @wire When:

    1. Automatic Updates: You want data to update automatically when parameters change.
    2. Simple Read-Only Data: For fetching data without requiring complex logic or user interaction.
    3. Performance: Need to use Salesforce’s cacheable Apex methods to improve performance.

Use Imperative Apex When:

    1. User Interaction: Execution depends on explicit user actions like button clicks.
    2. Dynamic Parameters: You need to pass parameters dynamically at runtime.
    3. Complex Error Handling: You want explicit control over error handling.
    4. Debugging: Easier to debug in some scenarios due to explicit invocation.

If you’re eager to dive deeper into the @wire approach or the imperative method of calling Apex classes, explore the detailed post below:

Conclusion

Both @wire and the imperative approach have their place in LWC development:

    • Use @wire for reactivity and scenarios where data needs to refresh automatically.
    • Use Imperative Apex for user-driven actions, dynamic inputs, or when you need greater control.

Understanding these methods’ strengths and limitations will help you make informed decisions and build more efficient LWC components.

Explore more Salesforce insights and best practices on Writtee. 🚀

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
Leave a comment