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

React componentWillUnmount hook (useEffect) with react hook (useState) array comes out empty?

Upon componentWillUnmount I want to send an array inside a useState to a postRequest function.

My useState array:

     const [array, setArray] = useState([]);

My componentWillUnmount function:

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

useEffect(() => {
    return () => {
      console.log(array); // logs "[]"
    // TODO: Send to a post request to BE
    }
  }, [])

I do also have a "normal" useEffect that listens on my useState array. When I add three elements inside it, the console logs shows there are three elemetns inside it

  useEffect(() => {
      console.log('array: ', array); // logs "(3) [{…}, {…}, {…}]" 
    }, [array]);

How come the array is empty in my componentWillUnmount function?

Edit: Adding array to the dependecy of the useEffect will make the function execute every time that array is updated, which is not what is desired. The function should only execute upon unmount with the values of the array

>Solution :

It’s because the value of the variable did not changed inside hook because it initiated on componentDidMount and did not received an update because the second parameter is empty.

Since you only want to trigger it once if the component unmounts and not every time the value changes:

you can use useRef to "preserve" the value without rerendering the component.

const ref = useRef();

useEffect(() => {
  ref.current = array;
}, [array]);

useEffect(() => {
  return function cleanup() {
    console.log(ref.current); // here is your array
  };
}, []);
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