DEV Community

Discussion on: How to use componentWillUnmount with Functional Components in React

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();
  }, []);