Better way is to listen to Gutenberg events. Template change can be observed with something like this:
wp.data.subscribe(() => {
console.log(wp.data.select( 'core/editor' ).getEditedPostAttribute('template'));
});
It will fire on many wp.data events, not only for template change. But you can add some checks and do your actions only when it’s needed. Example:
const editor = wp.data.select( 'core/editor' );
let lastTemplate = null;
wp.data.subscribe(() => {
if (lastTemplate != editor.getEditedPostAttribute( 'template' )) {
lastTemplate = editor.getEditedPostAttribute( 'template' );
console.log( 'current template:', editor.getEditedPostAttribute( 'template' ));
}
});
You cant also check post format:
console.log( 'post format:',
wp.data.select( 'core/editor' ).getEditedPostAttribute( 'format' ));
Adding and removing class is-hidden
is not enough, you need to change react component state with this Gutenberg method:
wp.data.dispatch( 'core/edit-post' ).toggleEditorPanelEnabled( 'meta-box-' + 'my-metabox' );
Similar to suggestion from this answer: https://wordpress.stackexchange.com/a/349926/168823