How do disable caching of custom block on a Magento 2 product view page?

Magento 2 Development

To disable caching of custom block on a Magento 2 product view page, you can implement to different approaches:

  • In a layout, set cacheable=”false”. Note that this attribute will make the whole product page non-cacheable.
  • Alternatively, you can set _isScopePrivate property to true in a block class. As a result, you will eliminate the aforementioned problem, but will achieve your goal: by implementing this approach, you instruct a page cache module to replace your block content with placeholder before caching. When the page is loaded from cache, your block can be rendered via Ajax request. Check \Magento\Captcha\Block\Captcha::__construct and related layouts/templates as an example.

More tips from Magento 2 Cookbook

Source (Magento Stackexchange Question) (Alex Paliarush)