I'm trying to access a ref during clean up (before the component unmounts).
Like so:
const Comp = () => {
const imgRef = React.useRef();
React.useEffect(() => {
console.log('component mounted', imgRef); // During mount, imgRef.current is always defined
return () => {
console.log('component unmounting', imgRef); // imgRef.current always null here
}
}, []); // also tried adding imgRef and imgRef.current still doesn't work in clean up
return (
<img src={'example.png'} ref={imgRef} />
);
};
const App = () => {
const [img, setImg] = React.useState(true);
return <div>
<button onClick={() => setImg(!img)}>toggle</button>
{img && <Comp />}
</div>;
};
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
Even adding imgRef
in the useEffect
's dependency, the imgRef.current is still null in the return of useEffect...
This works in the equivalent Class component with componentWillUnmount
the imgRef is properly defined.
How can I make it work with hooks?
const
with an object initially assigned to it should never beundefined
, so I'm doubtful...) – Ansilmeundefined
as your question says, it's null. Fix it with: stackoverflow.com/a/67069936 – Ansilmeconst img = imageRef.current
before the return and then you can access it in the return function. – Dispense