I am trying to refactor an old class component into a functional component with hooks and have got stuck with a componentWillUnmount
Previously the code had this:
componentDidMount() {
this.isDropdownMounted = true;
}
componentWillUnmount() {
this.isDropdownMounted = false;
}
My solution was to use to use a useEffect with a cleanup function but despite it 'appearing' to work it failed code review and I can't seem to find a better solution. I've read about potentially using a useRef but haven't stumbled across a similar use case just yet.
useEffect(() => {
isDropdownMounted = true;
return function cleanup() {
isDropdownMounted = false;
};
}, []);
Any ideas what I can try?
React doesn't remember isDropdownMounted variable. It will be recreated on each render. It will be better to use useRef hook to set value in useEffect and remember it on the next render.
const isDropdownMounted = useRef(null);
useEffect(() => {
isDropdownMounted.current = true;
return function cleanup() {
isDropdownMounted.current = false;
};
}, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With