I'm trying to build a functional component with hooks, that calls a function only once when it gets unmounted. In this function I need to access the components current state variables.
This codesandbox illustrates the core problem I'm facing
I know that I could pass the state variable in the useEffect dependency array, but in my real world example it is a requirement that the effect is only called once when the component unmounts, and adding it to the array would cause it to be called on every render.
Also I tried useCallback, useRef to the state variable and searched for similar use cases and examples without success and I feel like that I'm missing something.
Is there a way fulfil both requirements (only is called once and access to current state variables)?
Also here is my code of my example. The button mounts/unmounts the counter and what I'd like to achieve is, that the last value of the counter is printed when it disappears.
import * as React from "react";
import "./styles.css";
import { useState, useEffect } from "react";
const Counter = () => {
const [count, setCount] = useState(0);
useEffect(() => {
return () => {
// this should print the counters current value
console.log("Count was " + count + " when counter disappeard!");
};
}, []); // Empty because effect should only run when component unmounts
const handleClick = () => {
setCount(count + 1);
};
return <button onClick={handleClick}>{count}</button>;
};
export default function App() {
const [showCounter, setShowCounter] = useState(true);
// mount/unmount the counter
const handleClick = () => {
setShowCounter(!showCounter);
};
return (
<div className="App">
<button onClick={handleClick}>Show/Hide counter</button>
{showCounter && <Counter />}
</div>
);
}
I would be really glad if someone knows a way to solve this.