skip to Main Content

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

2

Answers


  1. 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);
      }
    }, []);
    
    Login or Signup to reply.
  2. 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

    You need to because without the dependency, the effect will use the data value at the time it is created

    A reminder

    The cleanup function runs not only during unmount, but before every re-render with changed dependencies. – ReactJS

    Here is a working sample: https://stackblitz.com/edit/vitejs-vite-houwrt?file=src%2FApp.tsx,src%2FComp.tsx&terminal=dev

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search