Drupal 8 has a very well structured system to show hide fields based on values of other fields. It is called the Form API #states system. You can see drupal.org documentation on #states.
While defining the form you can map the visible and invisible states of the form element based on the value of another form element.
This is an example from the documentation above
$form['toggle_me'] = array(
'#type' => 'checkbox',
'#title' => t('Tick this box to type'),
);
$form['settings'] = array(
'#type' => 'textfield',
'#states' => array(
// Only show this field when the 'toggle_me' checkbox is enabled.
'visible' => array(
':input[name="toggle_me"]' => array(
'checked' => TRUE,
),
),
),
);
There are other states besides visible and invisible that can be controlled through the same mechanism. Lullabot has a good article on Form API #states
Other states including making a field required is available. The full list is as follows.
enabled
disabled
required
optional
visible
invisible
checked
unchecked
expanded
collapsed