How to remove block cache problem in Drupal 8

remove block cache in drupal 8

Remove block cache in Drupal 8

By default Drupal 8 block cached it's contents,  that's why it's contents does not refresh every time when a page loads, so you needs to remove block cache programmatically.

In a Drupal 8 website, I use the same block on multiple pages, In this block I have written the code to  fetch the data through API request depending on the parameter comes in URL.

But the Drupal 8 was caching the block contents and I need to clear cache all the times to update the site contents.

So for remove the block cache problem, I have set the block cache max age.

$blocks['#cache']['max-age'] = 0;

You can change the block cache max age to use this hook

Write this code within your custom modules or your theme template


  * Implements hook_preprocess_HOOK()


function your_theme_name_preprocess_block(&$blocks) {

  if($blocks['derivative_plugin_id'] == 'your_block_name') {

    /* This code removes the block cache problem in Drupal 8 */

    $blocks['#cache']['max-age'] = 0;