The answer is exactly the same as an existing question you asked, even though the question was quite different.
The answer is: cache tags or more generic, cache metadata.
Quoting myself from https://drupal.stackexchange.com/a/160982/31:
Blocks are cached by default.
You don't need to manually clear those caches when you change your
configuration, but you need to flag/tag your blocks output to tell
Drupal that your block output depends on your configuration.
Read the Cacheability documentation. What you need is something
like this:
$output['#cache']['tags'] = $config->getCacheTags();
Just replace block with entity in the description and you have your answer. Note that when doing something conditional, you must always add the cache tags/context, meaning, outside of the if condition, not inside.
I just realized my code sample there is problematic when you alter existing render arrays, because you risk overwriting existing cache tags. So you should use what the referenced documentation does, that ensures that existing cache tags are kept:
\Drupal::service('renderer')->->addCacheableDependency($build, $config);
That basically reads "$build depends on $config".
Memorize that link and the steps there. Always check them you add or change render arrays:
The thought process
Please try to adopt the following thought process.
Whenever you are generating a render array, use the following 5 steps:
- I'm rendering something. That means I must think of
cacheability.
- Is this something that's expensive to
render, and therefore is worth caching? If the answer is "yes",
then what identifies this particular representation of the thing I'm
rendering? Those are the cache keys.
- Does the
representation of the thing I'm rendering vary per combination of
permissions, per URL, per interface language, per … something?
Those are the cache contexts. Note: cache
contexts are completely analogous to HTTP's
Vary
header. - What causes the representation of the thing
I'm rendering become outdated? I.e. which things does it depend
upon, so that when those things change, so should my representation?
Those are the cache tags.
- When does the
representation of the thing I'm rendering become outdated? I.e. is
the data valid for a limited period of time only? That is the
max-age (maximum age). It defaults to "permanently
(forever) cacheable" (
Cache::PERMANENT
). When the
representation is only valid for a limited time, set a max-age,
expressed in seconds. Zero means that it's not cacheable at all.
Cache contexts, tags and max-age must always be
set, because they affect the cacheability of the entire
response. Therefore they "bubble": parents automatically receive them.
Cache keys must only be set if the render array should be
cached.