How can I prevent user data being cached and showing the wrong 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