theming – How to use hook_field_preprocess to add a prefix/suffix to an entity reference field for different view modes?

I’m trying to move some markup from twig templates to hook_preprocess_field().

I have an entity reference field (media image) that I want to add a prefix and suffix to.

I added a prefix and suffix like this:

function MYMODULE_preprocess_field__MYFIELD(&$variables) {
  $prefix = 'Hi... ';
  $view_mode = $variables('element')('#view_mode');
  if ($view_mode == 'second_view_mode') {
    $prefix = 'Hello... ';
  }
  $suffix = '... there.';
  $variables('items')(0)('content')('#prefix') = $prefix;
  $variables('items')(0)('content')('#suffix') = $suffix;
}

With this code, my prefix and suffix get added, but they are cached, and the same for all view modes.

If I rebuild the cache and visit a node in second_view_mode, then I see Hello... as the prefix for all instances of the field. But if I rebuild the cache and visit a node not in second_view_mode, then I see Hi... for all instances of the field, even those on a node in second_view_mode.

I use this same approach/code for formatted text fields and I don’t experience this caching problem. So I think I need to do something different for this entity reference field, but I don’t know what to do.

How do I add a prefix/suffix to an entity reference field in a preprocess function for different view modes?