Unmount a component in reactjs

I did some research on “unmountComponentAtNode”, but still don’t quite get it, what is the difference between “unmountComponentAtNode” and below code(change state to unmount a component):

const Parent = () => {
    const [unmountChildComponent, setUnmountChildComponent] = useState(false);
    const handleUnmountChildComponent = () => {
        setUnmountChildComponent(true);
    };
    return (
        <div className='parent'>
            {!unmountChildComponent ? <Child /> : <div>No data</div>}
            <button onClick={handleUnmountChildComponent}>Unmount child component</button>
        </div>
    );
};

Above code and “unmountComponentAtNode” both can unmount a component, so my question is, which one is the correct way(best practice way) to unmount a reactjs component?

What are you trying to do? For normal React applications, you should just let React handle all that messy stuff. Your code example is how I would handle it, though I think the variables should be something like hasData and setHasData or whatever.

So what you mean is, basically in general, in reactjs applications if a component needed to get removed(unmount), this is how most people do it?(Below code)

const Parent = () => {
    const [unmountChildComponent, setUnmountChildComponent] = useState(false);
    const handleUnmountChildComponent = () => {
        setUnmountChildComponent(true);
    };
    return (
        <div className='parent'>
            {!unmountChildComponent ? <Child /> : <div>No data</div>}
            <button onClick={handleUnmountChildComponent}>Unmount child component</button>
        </div>
    );
};

so normally people don’t really use “unmountComponentAtNode” to remove(unmount) a component?

I think we are disagreeing about terminology here. I don’t “unmount” a component. I simply stop rendering it and let React unmount it as it sees fit.

What you are doing in the code is what I would call “conditional rendering”. As a professional React developer I have never used unmountComponentAtNode and having looked at it, I think that we should almost never need that.

In short, what you are doing with your code is a very common pattern. You can put ternary statements or && short circuits into your code, or you can do some kind of a return early pattern.

so normally people don’t really use “unmountComponentAtNode” to remove(unmount) a component?

That is correct. I’m a professional React developer and I’d forgotten that that actually exists.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.