How do I change the node view mode before rendering? I have a content type with a custom view mode. How do I make sure node always get rendered with my custom view mode?

What would be the right way to programmatically change the node view mode before rendering?
If you want to make sure that a content type is always rendered with a custom view mode, use the following hook in a module. (I assume the module machine name is mymodule.)

mymodule.module

/**
 * Implements hook_entity_view_mode_alter().
 */
function mymodule_entity_view_mode_alter(&amp;$view_mode, $entity, $context) {
  if ($entity-&gt;getEntityTypeId() == 'node' &amp;&amp; $entity-&gt;bundle() == 'my_content_type') {
    $view_mode = 'my_custom_view_mode';
  }
}