Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Component state persists after unmounting?

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading