Here in my React the clean up function is not executed when re-rendering:
import React, { useRef, useState } from 'react';
export default function App() {
const [x, setX] = useState(2);
const d = useRef(null);
return (
<>
<p ref={(node) => {
console.log('start');
return () => {
console.log('finish');
};
}}>{x}</p>
<button onClick={() => setX(x + 1)}>hello</button>
</>
);
}
i want my clean up function to be executed when the ref callback is updated hence here the callback is created every render then the clean up must be executed every render!
2
Answers
React refs don’t have a cleanup function in the same way the
useEffect
hook callback returns a cleanup function. React refs that are set with the callback syntax are simply just called again and passednull
.Example:
In the ref callback, check when the ref is null and handle any "cleanup" duties.
Note: It’s more conventional/standard to use a
useEffect
hook to run any cleanup logic.Ref cleanups are only available in canary builds of React, so currently not available in stable versions, if you want to play around with it, you need to use a canary build for the time being, or test for
null
like Drew suggests in his answer: