Search code examples
reactjsreact-hooksuse-effect

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:

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
      };
    }, []);