How to cache block for logged in user? I have a block, created with a custom block plugin (extending BlockBase),  that shows on every page, and I want to cache its data, to speed up  performance.

I have added cache tags to the build() function:

$build['#cache']['tags'] = $cache_tags;


But the build() function is still executing on each page load.  I guess because the cache tags are for render cache, not data cache.

Is there a built in way to cache the data in the build() function for a block for logged in users?

Or do I have to add custom caching in the build function, like this:

if ($cache = \Drupal::cache()-&gt;get($cid)) {


https://api.drupal.org/api/drupal/core!core.api.php/group/cache/8.2.x
Blocks are cached by default. A block class with this build method:

public function build() {
    return [
      '#markup' =&gt; 'Block content',
    ];
  }


gets cached indefinitely or as long as you set in cache max-age.

If you add cache tags to the block that doesn't change whether the block is cached or not. The cache tags are used to invalidate cache items, not to store them. That is what cache keys are used for.

If the block gets cached, this is for logged in users, because the cache for anonymous users doesn't cache blocks, only pages.