'on unmounting of component not getting the state value

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



Solution 1:[1]

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

Solution 2:[2]

Add dependency in hooks as it will change when you start typing and useEffect clean up function will give you last state

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user1672994
Solution 2 Dada