The Magento 2 caching is important for page load speed. Nevertheless, it causes trouble with the customizations that require the dynamic content output.
Not all the time can you go for the caching, based on your business requirements. But there’s a way out. You can disable cache for particular blocks only.
This way, you can disable cache for block using XML in Magento 2. For example, you have implemented a block that behaves differently for the desktop and mobile. If the user accesses it from desktop and then from mobile, he should see the difference which can be possible only if it is disabled to fetch the value from the cached version.
To implement such functionalities where you want Magento 2 to not fetch the cached version, use the solution below!
Method to Disable Cache for Block Using XML in Magento 2:
Add this cacheable=”false” into the XML file like:
<block class="Block\Class" name="blockname" cacheable="false" />
for example : [Vendor]\[Module]\view\frontend\layout\checkout_cart_index.xml
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<block class="[Vendor]\[Module]\Block\Custom" template="[Vendor]_[Module]::custom.phtml" before="-" name="custom_index" cacheable="false"/>
Use this method when you want to disable the cache for a particular block.
Any doubts on the topic can be mentioned in the Comments section below and I’d be glad to help.
Please feel free to share the solution with fellow developers via social media.