Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: Multiple renderings in the same dom without being overwritten, all renders are displayed #28727

Closed
qluwlh opened this issue Apr 3, 2024 · 2 comments

Comments

@qluwlh
Copy link

qluwlh commented Apr 3, 2024

In some cases, I need to render content multiple times in a DOM, and I expect the subsequent render to overwrite the previous content. However, in the code below, all the multiple render contents are displayed

React version: 18.2.0

Steps To Reproduce

  1. index.js
import { createRoot } from 'react-dom/client';
import App from './App.js';
import './styles.css';
const dom = document.getElementById('root')

const render = (Comp)=> {
  createRoot(dom).render(Comp)
}
render(<App/>)
render(<App/>)
  1. App.js
import { useState,useEffect } from 'react';

export default function App() {
  const [show,setShow] = useState(false)
  useEffect(()=> {
    setTimeout(()=>{
      setShow(true)
    },500)
  },[])
  if(!show){
    return <></>    //  I found that when this place returns a non empty value, this problem will not occur anymore
  }
  return (
    <>
      <h1>Hello, world!</h1>
      <Counter />
    </>
  );
}

The current behavior

The content of both renderings has been preserved
image

The expected behavior

Only the last one will be retained

@qluwlh qluwlh added the Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug label Apr 3, 2024
@eps1lon
Copy link
Collaborator

eps1lon commented Apr 3, 2024

This is expected since you create multiple roots. If a render should overwrite the previous one, create the root just once:

const root = createRoot(container);
root.render(<App />)
root.render(<App />)

@eps1lon eps1lon closed this as not planned Won't fix, can't repro, duplicate, stale Apr 3, 2024
@eps1lon eps1lon added Resolution: Expected Behavior and removed Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug labels Apr 3, 2024
@qluwlh
Copy link
Author

qluwlh commented Apr 3, 2024

Why is returning a null value not overwritten, while returning a value can be overwritten? The behavior of the two is inconsistent.

 if(!show){
    return <></>   // Will not be covered
  }
 if(!show){
    return <div>value</div>   //  Will be covered
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants