How to avoid certain variables from being cached? I've spent days trying to figure this out and really hope you guys can help me out here.

Let's say, I’ve created a list field on the user entity called field_render_array with the options:


Render array 1   
Render array 2


There is a controller called RenderArray which should:


Return render array 0 if field_render_array is not set. 
Return render array 1 if field_render_array is equal to render_array_1.
Return render array 2 if field_render_array is equal to
render_array_2.


I’ve been trying to achieve this using a controller like:

&lt;?php

namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;

class RenderArrayController extends ControllerBase {

  public function content() {
    $user = \Drupal::currentUser();
    $field_render_array = $user-&gt;get(‘field_render_array’)-&gt;value;

    if (!isset($field_render_array)) {
      return array(
        ‘#markup' =&gt; ‘You haven’t set your preferred render array.',
      );
    }
    else if ($field_render_array == ‘render_array_1’ ) {
      return array(
        ‘#markup' =&gt; ‘Your preferred render array is 1',
      );
    }
    else {
      return array(
        ‘#markup' =&gt; ‘Your preferred render array is 2’,
      );
    }
  }

}


The problem is that the value of $field_render_array is getting cached. This comes across as a bug for end-users as the render array doesn’t immediately change after changing the value of field_render_array.

Is it possible to somehow avoid certain variables from being cached or is there another solution to achieve the same thing?
If the variables come from the current user, then add this cache context to the build array you return:

$build['#cache']['contexts'][] = 'user';