How to correctly use cookies? (Twig and cache context)
I've updated the code in the question, the code is now working. It was almost complete, I had made some simple mistakes though:


Even when providing a proper cache context, you still need to disable the Internal page cache module. Only Internal dynamic page cache module is allowed.
user_cookie_save() prefixes the cookie name with Drupal.visitor. This is  the real name you'll also see in your browser's dev console. But when checking for cookie names in PHP, dots and spaces are converted to underscores. That means using user_cookie_save(['mycookie' =&gt; 'some_value']); creates a cookie with a "real" name of Drupal.visitor.mycookie, but in PHP


your template/module code needs to check
if ($_COOKIE['Drupal_visitor_mycookie'])
and you also have to use the underscore name in services.yml
required_cache_contexts: ['cookies:Drupal_visitor_device', '...other_stuff...']

Don't set the cookie value and check that updated cookie value in the same request:
user_cookie_save(['mycookie' =&gt; 'new_value'])
will immediatly update the cookie in the client browser, but PHP code in the same request like
if ($_COOKIE['Drupal_visitor_mycookie'])
will still return the original value from the previous request.