Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useEffect as componentWillUnmount

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?

like image 531
Serdar Mustafa Avatar asked Dec 14 '25 07:12

Serdar Mustafa


1 Answers

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;
    };
  }, []);
like image 188
lissettdm Avatar answered Dec 16 '25 22:12

lissettdm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!