ComponentWillUnmount equivalent with React Hooks that has access to the current values of state variables?

Viewed 130

I'm trying to build a functional component with hooks, that calls a function only once when it gets unmounted. In this function I need to access the components current state variables.

This codesandbox illustrates the core problem I'm facing

I know that I could pass the state variable in the useEffect dependency array, but in my real world example it is a requirement that the effect is only called once when the component unmounts, and adding it to the array would cause it to be called on every render.

Also I tried useCallback, useRef to the state variable and searched for similar use cases and examples without success and I feel like that I'm missing something.

Is there a way fulfil both requirements (only is called once and access to current state variables)?

Also here is my code of my example. The button mounts/unmounts the counter and what I'd like to achieve is, that the last value of the counter is printed when it disappears.

import * as React from "react";
import "./styles.css";
import { useState, useEffect } from "react";

const Counter = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    return () => {
      // this should print the counters current value
      console.log("Count was " + count + " when counter disappeard!");
    };
  }, []); // Empty because effect should only run when component unmounts

  const handleClick = () => {
    setCount(count + 1);
  };

  return <button onClick={handleClick}>{count}</button>;
};

export default function App() {
  const [showCounter, setShowCounter] = useState(true);

  // mount/unmount the counter
  const handleClick = () => {
    setShowCounter(!showCounter);
  };

  return (
    <div className="App">
      <button onClick={handleClick}>Show/Hide counter</button>
      {showCounter && <Counter />}
    </div>
  );
}

I would be really glad if someone knows a way to solve this.

2 Answers

Another solution would be to save the state in a ref and have a seperate useEffect hook which updates the ref when the state changes. Then you can access the "last" state via the ref object.

Example: https://codesandbox.io/s/trusting-diffie-8tiev

Related