microsoft / use-disposable

Creating instances in React during render that need to be disposed even with StrictMode
MIT License
11 stars 5 forks source link

Return value `null` on first render #28

Open smeijer opened 9 months ago

smeijer commented 9 months ago

The readme lists a portal example, with output:

import * as React from "react";
import * as ReactDOM from "react-dom";
import { useDisposable } from "use-disposable";

function Portal({ children }) {
  const domNode = useDisposable(() => {
    const newElement = document.createElement("div");
    document.body.appendChild(newElement);
    console.log("create DOM node");
    return [newElement, () => newElement.remove()];
  }, []);

  console.log("render to portal");
  return ReactDOM.createPortal(children, domNode);
}

The output

create DOM node
render to portal
render to portal

Yet when I run that code, the output is as below, domNode is null on the first render, and no portal is shown.

render to portal
create DOM node
render to portal

Reproduction here: https://stackblitz.com/edit/react-t1nu78?devToolsHeight=33&file=src%2FApp.js