My suggestion is to use Layout Handle to update the current layout.
app/code/Vendor/Module/etc/frontend/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Helper\Product\View">
<plugin name="outofstock_layout" type="Vendor\Module\Plugin\Helper\Product\View"/>
</type>
</config>
app/code/Vendor/Module/Plugin/Helper/Product/View.php
<?php
namespace Vendor\Module\Plugin\Helper\Product;
use Magento\Catalog\Model\Product;
use Magento\CatalogInventory\Model\Stock\StockItemRepository;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Result\Page;
class View
{
/**
* @var StockItemRepository
*/
protected $stockItemRepository;
/**
* View constructor.
*
* @param StockItemRepository $stockItemRepository
*/
public function __construct(
StockItemRepository $stockItemRepository
) {
$this->stockItemRepository = $stockItemRepository;
}
/**
* @param \Magento\Catalog\Helper\Product\View $subject
* @param Page $resultPage
* @param Product $product
* @param $params
* @return array
*/
public function beforeInitProductLayout(\Magento\Catalog\Helper\Product\View $subject ,$resultPage, $product, $params){
try {
$productStock = $this->stockItemRepository->get($product->getId());
if (!$productStock->getIsInStock()) {
$resultPage->getLayout()->getUpdate()->addHandle('catalog_product_view_outofstock');
}
} catch (NoSuchEntityException $noSuchEntityException) {
// Do no thing
}
return [$resultPage, $product, $params];
}
}
Here is the new Layout handle for out of stock:
app/code/Vendor/Module/view/frontend/layout/catalog_product_view_outofstock.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="product.info.media" remove="true"/>
<referenceBlock name="product.info.details" remove="true"/>
<referenceBlock name="product.info.description" remove="true"/>
</body>
</page>