DEV Community

How to use componentWillUnmount with Functional Components in React

Robert Marshall on May 17, 2020

Most up to date version of this article: https://robertmarshall.dev/blog/componentwillunmount-functional-components-react Functional componen...
Collapse
 
sridhar_natuva profile image
sridhar.natuva

I want to display an dialog box on unmount and When user cancels it should stop unmounting the component.

Right now, even if user cancels or says ok, component will anyway unmount on return funtion.

Is there any way to stop unmount on the return function? Or any other approach?

Collapse
 
arnabmunshi profile image
ARNAB MUNSHI

Hi, I need a help

  componentDidMount() {  
    this._subscribe();
  }

  componentWillUnmount() {
    this._unsubscribe();
  }

  async _subscribe() {
    const batteryLevel = await Battery.getBatteryLevelAsync();
    this.setState({ batteryLevel });
    this._subscription = Battery.addBatteryLevelListener(({ batteryLevel }) => {
      this.setState({ batteryLevel });
      console.log('batteryLevel changed!', batteryLevel);
    });
  }

  _unsubscribe() {
    this._subscription && this._subscription.remove();
    this._subscription = null;
  }

How to convert this in functional component ?
I have done something like this ...

  const getLevel = async () => {
    console.log("A: " + (await Battery.getBatteryLevelAsync()));

    let batteryLevel = Math.round((await Battery.getBatteryLevelAsync()) * 100);
    setLevel(batteryLevel);
    Battery.addBatteryLevelListener(({ batteryLevel }) => {
      batteryLevel = Math.round(batteryLevel * 100);
      setLevel(batteryLevel);

      console.log("B: " + batteryLevel);
    });
  };

  useEffect(() => {
    // Anything in here is fired on component mount.
    // componentDidMount
    getLevel();

    // componentWillUnmount
    return () => {
      // Anything in here is fired on component unmount.
    };
  }, []);

I am facing problem in

return function

Collapse
 
robmarshall profile image
Robert Marshall

If you don't need anything to fire on component unmount, you can remove the return.

  useEffect(() => {
    getLevel();
  }, []);
Collapse
 
gopeeey profile image
gopeeey

Thank you very much for this

Collapse
 
amahecool profile image
amahecool • Edited

the returned function fires on component Re-render also. How to you check if its an unmount or just a re-render ?
Basically its just a clean up function which runs every time the useEffect is used (except the first time)

Collapse
 
kasir-barati profile image
Mohammad Jawad (Kasir) Barati • Edited

Are you sure? AFAIK it should not be the case, it's only triggered once the component is unmounting or remounting itself. So maybe you can check that out.

Also you might have other useEffect who are defined sooner and as you might know the order of defining useEffect hooks matter

Collapse
 
robmarshall profile image
Robert Marshall

I suppose you could use a useRef to track the render (it will not be cleaned on a rerender). Depends on what you need it to do.

Collapse
 
vladanpro profile image
Vladan Profirovic

import React, { useEffect } from 'react';
const ComponentExample => () => {
useEffect( () => {
// Anything in here is fired on component mount.
}, []);
}
hi srry this show me that is fired on component mount but not on will mount, so i try to find what is best solution to replace componentWillMount. Tnx.

Collapse
 
rahulbhadhoriya profile image
Rahul Bhadhoriya

Thanks very much

Collapse
 
omnislashbr profile image
Hector Bonilha

This is going to simulate componentDidUnmount, not componentWillUnmount

Collapse
 
kasir-barati profile image
Mohammad Jawad (Kasir) Barati

Hm, interesting. Can you explain it further in detail?

Collapse
 
shivam164 profile image
Shivam

Nice this is what I was searching for :).

Collapse
 
seojeek profile image
Alex Vallejo

"Parsing error: Unexpected token, expected ","" is what i get when i try to return that

Collapse
 
robmarshall profile image
Robert Marshall

Looks like you have a typo?

Collapse
 
pablobion profile image
Pablo Bion

Very cool!

Collapse
 
kasir-barati profile image
Mohammad Jawad (Kasir) Barati

BTW I believe this Stackoverflow Q&A would be a real complimentary content to your post: stackoverflow.com/q/77221997/8784518

Collapse
 
ankitalphaq profile image
Ankit Kumar Gupta

Hey, do we have some restrictions with using the current state values inside ComponentWillUnmount cleanup function ?
Few of my state values are reseted before my code could run 😔

Collapse
 
robmarshall profile image
Robert Marshall

Able to give a bit more context? If you are passing this state out of the component (e.g. to a parent) and then unmounting this component I imagine you would have problems.

Collapse
 
umeredava profile image
Umar Sanil

Thanks