Search code examples
reactjsreact-hooks

Can i call componentWillUnmount (functional component) with current data?


I have a functional component

export const Example = () => {
    const [data, setData] = useState<number>(0);

    useEffect(() => {
        return () => {
            console.log("data", data);
            // ----> Here i want current value of data at the componentWillUnmount
        };
    }, []);

    return (
        <div>
            <button onClick={() => setData((prev) => prev + 1)}>Inc</button>
            {data}
        </div>
    );
};

Lets say i rendered this component, clicked 5 times at button. Then i unmounting this component. Can i somehow call console.log inside componentWillUnmount ("return" inside "useEffect" for func components) with current (4) value of data?

Note: i can not pass data as a deps in useEffect cause i dont want to see console.log`s with data every time data changes


Solution

  • Yeah, you can use a ref to jot down the latest value of data, then access the ref in the cleanup function.

    const [data, setData] = useState<number>(0);
    const ref = useRef(data);
    ref.current = data;
    useEffect(() => {
      return () => {
        console.log("data", ref.current);
      }
    }, []);