When you define your effect like
useEffect( () => () => console.log( ["unmount",data1] ), [] );
You essentially tell it to run on initial render and hence the data1 that the callback points to is the initial value that it inherited from the closure and is never updated since the function is no longer initialised
If at all, for any reason you want the data1 to be accessible in useEffect
you must pass it as the second argument to useEffect
useEffect( () => () => console.log( ["unmount",data1] ), [data1] );
In such a case the effect will be cleaned up any change of data1
You could also make use of useRef
to store the data and access it in unmount.
function App() {
const [data1, setData1] = useState(0);
const refAttr = useRef();
useEffect(
() => () => {
console.log("unmount", refAttr.current);
},
[]
);
useEffect(() => {
setInterval(() => {
setData1(data1 => {
refAttr.current = data1 + 1;
return data1 + 1;
});
}, 1000);
}, []);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
Working demo