How can I prevent user data being cached and showing the wrong username? I have built a Drupal 8 site, we are showing the user name and last name on a block, this is my code on preprocess from .theme file:

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()-&gt;id());

$firstname = $user-&gt;get('field_firstname')-&gt;value;

$firstname = $firstname;
$variables['firstname'] = $firstname;


Then in the block im doing: Hello {{ firstname }}

And it shows the last user, not mine. When I do drush cr then I get the correct name, why? How can I fix this and already display the right username?
You are retrieving the user name from the current context and the user entity, but then you make it a dumb string value to pass it to the template. Include the cache metadata to define where this value is coming from and under which circumstances it could change:

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()-&gt;id());
$firstname = $user-&gt;get('field_firstname')-&gt;value;

$variables['firstname'] = [
  '#plain_text' =&gt; $firstname,
  '#cache' =&gt; [
    'contexts' =&gt; ['user'],
    'tags' =&gt; $user-&gt;getCacheTags(),
  ],
];


More info https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays