to run this code after leaving the checkout page, and it works, but is there a better way? The above will needlessly be executed for every page change.
does the shipping really have to be removed when you leave the page? you could simply removeAllShipping before entering the route where the user gets to addShipping again. I guess this is kind of what @bvdputte already suggested.
otherwise if your route works, maybe just throw in another condition so the entire function doesn’t have to be called on each load (assuming removeAllShipping() is a little bit more complex)
if ($path !== 'checkout' && $hasShipping) {
removeAllShipping();
}