Drupal 8 - Variables - Template Twig - Cache In the HOOK of my project XXX_preprocess I am defining a variable based on a cookie.

My Hook function

function XXXXXX_preprocess(array &amp;$variables) {
if (isset($_COOKIE[personsSearchCookie]) &amp;&amp; !empty($_COOKIE[personsSearchCookie])) {
    $personsFilter = explode("-", $_COOKIE[personsSearchCookie]);
    $variables["personsFilter"] = array (
        "filterType" =&gt; $personsFilter[0],
        "filterId" =&gt; $personsFilter[1]
    );
}


But in the Twig template, it always gives me the initial value of that variable, it never changes.
My Twig code:

Filtering results by [{{ personsFilter.filterType }}]&lt;br /&gt;

{% if personsFilter is defined and personsFilter.filterType is defined and personsFilter.filterType is not empty %}
    {% if personsFilter.filterType == "area" %}
        Filtering by Area &lt;br /&gt;      
    {% endif %}

    {% if personsFilter.filterType == "office" %}
        Filtering by Office &lt;br /&gt;
    {% endif %}
{% else %}
    No filtering
{% endif %}


This should be a cache theme, right?

How can I make so that when my cookie changes, the variable is modified and since twig can access the new value?

In the prepreocess function in all re-loads, the variable change correctly, but, in twig, the variable have bad value.

Thank you!
In your question, it wasn't clear how you are defining the render array (a block, a form, etc.) Assuming you are rendering this twig file through a render array, you could add the following to the render array for this particular element to turn off caching of this element:

 '#cache' =&gt; [
    'max-age' =&gt; 0,
  ],


You could get more specific by implementing conditional logic to clear the cache on a certain condition. From the examples module, in the cache_example, we have the CacheExampleForm function createExpiringItem():

/**
* Submit handler to create a new cache item with specified expiration.
*/
public function createExpiringItem($form, &amp;$form_state) {

$tags = array(
  'cache_example:1',
);

$interval = $form_state-&gt;getValue('expiration');
if ($interval == 'never_remove') {
  $expiration = CacheBackendInterface::CACHE_PERMANENT;
  $expiration_friendly = $this-&gt;t('Never expires');
}
else {
  $expiration = time() + $interval;
  $expiration_friendly = format_date($expiration);
}
// Set the expiration to the actual Unix timestamp of the end of the
// required interval. Also add a tag to it to be able to clear caches more
// precise.
$this-&gt;cacheBackend-&gt;set('cache_example_expiring_item', $expiration_friendly, $expiration, $tags);
drupal_set_message($this-&gt;t('cache_example_expiring_item was set to expire at %time', array('%time' =&gt; $expiration_friendly)));
}


And, also shown in the examples is invalidating:

$tags = array(
  'cache_example:1',
);
Cache::invalidateTags($tags);


So in your preprocess, you could use this type of logic to invalidate the cache. Hope this helps.