I thought I understand everything about React by now, but I can't make this simple use case work. I need to run a function when the component unmounts, to tell another system, that an announced data update can be discarded.
My approach was to useEffect
with an empty dependency array, which works, but is wrong according to ESLint and the React docs.
Approach 1: Don't add the reactive value (input) to the dependency array
This works, but according to the React Docs is wrong and will introduce bugs.
Approach 2: Add the reactive value to the dependency array
This won't work, since the clean-up function will run every time the value changes, not just when the component unmounts.
import { useEffect, useState } from "react";
function MyComponent({ updateId }: { updateId: string }) {
const [input, setInput] = useState("");
useEffect(() => {
return () => {
// This should only run when the component unmounts, but must access the input value
if (input === "") {
// discard update
}
// For this example just print the value
console.log(input);
};
}, []);
return <input value={input} onChange={(e) => setInput(e.target.value)} />;
}
What is the solution for this problem? I found another question concerning this on StackOverflow which suggested a workaround using useRef
, but this seems also hacky. There has to be a simple way for this trivial requirement. In Svelte I would just use the onDestroy
lifecycle function.