Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

on unmounting of component not getting the state value

Tags:

reactjs

I have a state variable where i am having the value, so on before unmounting i need to log this to some analytics. So when i access the state it shows me as undefined. So before unmount i need to get this data.

const [name, setName] = useState(null);

useEffect(() => {
  return () => {
    console.log(name) // null
  }
}, [])

<input value={name} onChange={e => setName(e.target.value)} />

here the last value before mounting i am not getting. How can i get this value before mounting happens

like image 520
dev Avatar asked Dec 11 '25 21:12

dev


2 Answers

In our project we are using a custom hook useIsMounted for that purpose: (we did not invent this - there are lot's of sources to be found). By using the standard useEffect logic with name as dependency, every keystroke will cause the code to trigger, which was not desirable in our case. We just wanted a single trigger on unmount.

import {useEffect, useRef } from 'react';

//custom hook outside the component to detect unmount
export default function useIsMounted() {
    const isMounted = useRef(false)
    useEffect(() => {
        isMounted.current = true
        return () => {
            isMounted.current = false
        }
    }, [])
    return () => isMounted.current
}

storing that under hooks/mounted.js you can use it like in this example

import useIsMounted from '../hooks/mounted'

export default function AnyComp() {

    const mounted = useIsMounted()

    const [name, setName] = useState(null)

    useEffect(() => {
        console.log('AnyComp mounted')
        return () => {
            if (!mounted()) {
                console.log('AnyComp unmounted', name)
            }
        };
    }, [mounted])

    return (
        <input value={name} onChange={e => setName(e.target.value)} />
    )
}

The console.log now should reflect the actual value of your state variable!

like image 73
Byron Star Avatar answered Dec 13 '25 18:12

Byron Star


You need to add the name as dependency at useEffect so that react runs the effect when name state value is updated. Also while unmounting it would have the latest state bind for name property.

useEffect(() => {
    return () => {
      console.log(name);
    }
  }, [name]);

You can read about useEffect at react.org

like image 21
user1672994 Avatar answered Dec 13 '25 19:12

user1672994



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!