Say I have a React component which has some async function, like a setTimeOut function which performs a task on the DOM element of that component. If the component unmounts during that setTimeOut, how would I prevent that async function from firing? The resulting function that fires throws an error since the DOM element no longer exists due to the component unmounting.
I'm attempting to ask a general question about theoretical ways to go about this, since I have quite a specific—but quite uncommon—use-case that essentially got no views in a previous question. The specific use-case that I have involves calling destroy() on a pixi-react-fiber graphics component after an animation completes, when sometimes the component has been unmounted during the animation. I think the general form of this question should be able to help me understand an approach.
edit: adding example
Container.js
const CursorContainer = props => {
const [darkMode, setDarkMode] = useState(props.darkMode)
useEffect(() => {
setDarkMode(props.darkMode)
}, [props.darkMode])
return (
<Cursor darkMode={darkMode} />
)
}
export default CursorContainer
Cursor.js
const TYPE = "Cursor"
export const behavior = {
customDisplayObject: props => new PIXI.Graphics(),
customApplyProps: function (g, _, props) {
const { darkMode } = props
g.clear()
g.beginFill(darkMode ? 0x7225e6 : 0xd3fc03, 1)
g.drawCircle(0, 0, 20)
g.endFill()
setTimeout(() => g.destroy(), 5000)
},
}
const Cursor = CustomPIXIComponent(behavior, TYPE)
export default Cursor
If the darkMode is toggled, the Cursor component will be unmounted and remounted due to the state change. If this happens during the 5s setTimeOut, it will throw an error, since the graphics DOM element of the component will be gone and there will be nothing to destroy. How do I prevent this function from firing if the component has been unmounted?