Lee Jongseo
Lee Jongseo

Reputation: 241

Why does react 18 warn using createRoot inside the container?

I'm using React 18 and nextjs and I made a kind of render function like this

export const showAlert = (props: AlertProps) => {
  // it will catch <div id="alert"></div> inside _document.tsx
  const container = document.getElementById('alert')
  if (container) {
    const root = createRoot(container)
    root.render(<Alert {...props} />)
  }
}

And I want to use this function like this

const handleClick = () => {
  if (error) {
    showAlert({
      type: "error",
      text: "Error !"
    })
  }
}

But React warn of this behavior:

enter image description here

Anyone knows why React warn using of createRoot for the render function ?

Upvotes: 0

Views: 461

Answers (2)

Drew Reese
Drew Reese

Reputation: 203373

You should only call createRoot on a specific container once during runtime. Update the logic to create and cache an alert root.

Example:

let root: Root | null = null;

const showAlert = (props: AlertProps) => {
  const container = document.getElementById("alert");
  if (container) {
    root = root ?? createRoot(container);
    root.render(<Alert {...props} />);
  }
};

Upvotes: 0

Lee Jongseo
Lee Jongseo

Reputation: 241

During runtime, createRoot should be called only once

Upvotes: 0

Related Questions