Remove Header and Footer if user is not logged on

You have a lot of ways to do this.

The first important thing is next: You must have a header or a footer (default header and footer, from WP) if you want to have functionality.

E.g If you are loaded scripts or styles in function.php they will be broken, because you can’t load them without header or footer.

You can create more types of footers or headers where if you have one page or one type of page templates you can do that on this way:

// your example-template.php
    
<?php /* Template Name: Example Template */
if(!is_user_logged_in()) {
    get_header('blank-header');
}   

And for the footer do the same thing.

In your case, where you want to load or not header and footer from the function, you can use 'init' hook or you can use the last hook before loading the template is 'template_redirect' that is your choice.