Skip to content

Components keep being added when updating state #4274

@yy0931

Description

@yy0931
  • Check if updating to the latest Preact version resolves the issue

I'm having a problem where a component is repeatedly added to document.body, even though it's only used once in the component. Below is a simplified version of the code, where <B /> keeps getting added repeatedly. This issue doesn't happen with React. Am I missing something?

import { render } from "preact"
import { useEffect, useState } from "preact/hooks"

const B = () => <div>B</div>

const Test = () => {
    const [state, setState] = useState(true)
    useEffect(() => {
        const timer = setInterval(() => {
            setState((s) => !s)
        }, 250)
        return () => { clearInterval(timer) }
    }, [])

    if (state) {
        return <div>
            <B />
            <div></div>
        </div>
    } else {
        const cond = false
        return <div>
            <div></div>
            {cond && <div></div>}
            <B />
            <div></div>
        </div>
    }
}

render(<Test />, document.body)

To Reproduce, you can copy-paste the above code to https://preactjs.com/repl to see that the text "B" is continuously added.

Expected behavior
Only a single instance of <B /> should be shown.

Edit: I've further simplified the code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions