On React hook component unmount, unable to get updated state variable value

Viewed 568

After clicking on "Click me" button my count value is updating. Now I have to Do Something if count is grater then 0 before my component unmount.

But I have noticed during debugger count value is always 0. While I was expecting count should be grater then 0 if I clicked multiple times.

Please help me, how to get updated value during component unmount. Thanks

import React, { useState, useEffect } from 'react';

function Example() {
    const [count, setCount] = useState(0);

    useEffect(() => {
    //ComponentDidMount 

    return(()=>{                        
        //componentWillUnmount
        alert(count); //count 0  
        if(count){
            //Do Something                
        }           
    })        
    },[]);

    useEffect(() => {
    document.title = `You clicked ${count} times`;        
    });

    return (
    <div>
        <p>You clicked {count} times</p>
        <button onClick={() => setCount(count + 1)}>
        Click me
        </button>
    </div>
    );
}
1 Answers

You are forming a closure over the original value of count when you set up your cleanup function in the useEffect. That means that even as the value of count updates in the state, the value of count stays as 0 in the cleanup function.

To avoid this, you need to add count to the array of dependencies for your useEffect. That way, when count updates in state, and the component re-renders, the cleanup function also updates with the latest value of count.

useEffect(() => {
  return (()=> {                        
    alert(count); // this will now be latest value of count on unmount
    if(count) {
      // Do Something                
    }           
  })        
}, [count]); // add is now a dependency of useEffect 
Related