Problem to display name from current logged I've created a custom block to display info from current user. When i'm logged with username "David", i see on my custom block the username from my last login with other user account.

I have to clear the cache to see the correct username from current user logged.

See here my code :

    class UserProfilBlock extends BlockBase {

  public function build() {

    $userinfo = [];

    $account = \Drupal::currentUser();
    $uid = \Drupal::currentUser()-&gt;id();

    $user = \Drupal\user\Entity\User::load($uid);

    $userinfo['name'] = $user-&gt;get('name')-&gt;value;


    return [
      '#username' =&gt; ucfirst($userinfo['name']),
      '#theme' =&gt; 'user_info_block',
    ];


  }

  public function blockForm($form, FormStateInterface $form_state) {
    $config = $this-&gt;getConfiguration();

    return $form;
  }

  public function blockSubmit($form, FormStateInterface $form_state) {
    $this-&gt;configuration['userprofilinfo_settings'] = $form_state-&gt;getValue('userprofilinfo_settings');
  }
}


Something is wrong on my custom module ?
I guess the problem is the block is cached for every user. You have to tell Drupal that it should be cached depending on the current logged in user. To do this you have to make use of Cache Tags.

In your case, you have to tell Drupal that the cache of that block should be invalidated when the current logged in user changes. That's because a Cache Context (the user) has changed. 

How to do it? You are returning a Render Array, a structure that tells Drupal how to render certain data. In the render array you can set the cache contexts that affect this render array (if the context changes then the cached data changes). In the specific page that talks about the Cacheability of Render Arrays you can see an example of a render array that is cached for each user:

$build = [
  '#markup' =&gt; t('Hi, %name, welcome back to @site!', [
    '%name' =&gt; $current_user-&gt;getUsername(), 
    '@site' =&gt; $config-&gt;get('name'), 
  ]),
  '#cache' =&gt; [
    'contexts' =&gt; [ 
      // The "current user" is used above, which depends on the request, 
      // so we tell Drupal to vary by the 'user' cache context.
      'user', 
    ],
  ], 
];


So, I guess that you should add the #cache key to your render array, probably in your theme function, but it may work in the build function (long time since I don't do theming, so I'm not sure).

The code to add is: 

'#cache' =&gt; [
  'contexts' =&gt; ['user']
]