Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destroy root Preact node?

I want to destroy the root Preact DOM node. I initially render my component as follows:

import { h, render } from 'preact';
import App from "./components/App";

render(<App />, document.querySelector("#app");

How do I destroy App? Do I simply unmount the #app DOM node, or does Preact offer a method similar to React's unmountComponentAtNode() method?

like image 932
Daniel Apt Avatar asked Feb 28 '26 01:02

Daniel Apt


2 Answers

Disclaimer: I work on preact.

Any rendered preact app can be easily destroyed by passing null to render:

render(null, document.querySelector("#app"));

We don't need any special functions to do that and have chosen to keep a small API surface area. The implementation for unmountComponentAtNode in preact-compat does literally just call render with null:

// Excerpt from compat for Preact X
function unmountComponentAtNode(container) {
    if (container._prevVNode!=null) {
        render(null, container);
        return true;
    }
    return false;
}
like image 182
marvinhagemeister Avatar answered Mar 02 '26 14:03

marvinhagemeister


There is no method like unmountComponentAtNode() without preact-compat. A workaround is to use the third argument of the render() method to replace the component you want to unnmount by '' or null like suggested here : https://github.com/developit/preact/issues/53#issuecomment-184868295

like image 31
SylvainF Avatar answered Mar 02 '26 13:03

SylvainF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!