Home > database >  Component state persists after unmounting?
Component state persists after unmounting?

Time:01-14

Consider the following code:

function Middle() {
    const [show, setShow]=useState(false);

    return (
        <div>
            <button onClick={()=>setShow(v=>!v)}>MIDDLE</button>
            <Bottom visible={show}/>
        </div>
    );
}


function Bottom(props) {
    const {visible} = props;
    const state = useRef(0);
   
    useEffect(() => {
        console.log('Hey', state.current  );
    });

    return (
        <>
            {visible && <div>BOTTOM</div> }
        </>
    );
}

Whenever we click on button MIDDLE, mounts/unmounts successively; at least this is my understanding, since it is added/removed into/from the DOM. Hence, what I should expect is not to persist its state. Instead, what it does happen is that state.current always increases its value. I am really confused...

CodePudding user response:

Still when visible value is false your Bottom component is described in your component tree. so that component never get unmounted but what actually get unmounted is the div element.

However if you do,

function Middle() {
    const [show, setShow]=useState(false);

    return (
        <div>
            <button onClick={()=>setShow(v=>!v)}>MIDDLE</button>
            {show && <Bottom visible={show}/>}
        </div>
    );
}

Now your Buttom component get unmount when show false. This time your ref will be reset back to it's initial value as component get remounted freshly when show true.

Or if you are actually trying to reset your component you can use key prop. Just pass a different key value to your component when you need to reset your component.

  • Related