I have a functional component
export const Example = () => {
const [data, setData] = useState<number>(0);
useEffect(() => {
return () => {
console.log("data", data);
// ----> Here i want current value of data at the componentWillUnmount
};
}, []);
return (
<div>
<button onClick={() => setData((prev) => prev + 1)}>Inc</button>
{data}
</div>
);
};
Lets say i rendered this component, clicked 5 times at button. Then i unmounting this component. Can i somehow call console.log inside componentWillUnmount ("return" inside "useEffect" for func components) with current (4) value of data?
Note: i can not pass data as a deps in useEffect cause i dont want to see console.log`s with data every time data changes
2
Answers
Yeah, you can use a ref to jot down the latest value of
data
, then access the ref in the cleanup function.You need to because without the dependency, the effect will use the
data
value at the time it is createdA reminder
Here is a working sample: https://stackblitz.com/edit/vitejs-vite-houwrt?file=src%2FApp.tsx,src%2FComp.tsx&terminal=dev