I am not clear how to deal with this, when the warning wants me to put a function as a dependency, since functions do not keep their identity across renders. What I've read is to put the function inside the effect directly, but that doesn't work in my case since I'd have to duplicate the function, as it's needed outside the effect as well. Here is a slimmed down version of my component:
import * as React from 'react';
import trapTabKey from '/trapTabKey';
const { useEffect, useRef, useState } = React;
export default function FullScreen(props) {
const [fullScreen, setFullScreen] = useState(false);
const divRef = useRef(null);
const handleKeyPress = (e) => {
const key = e.which || e.charCode || e.keyCode;
// Escape
if (key === 27) {
document.body.classList.remove('full-screen-open');
setFullScreen(false);
// Tab
} else if (key === 9 && fullScreen) {
const domNode = divRef.current;
trapTabKey(e, domNode);
}
};
useEffect(() => {
document.body.addEventListener('keydown', handleKeyPress);
return () => {
// I need to bind handleKeyPress to the body here
document.body.removeEventListener('keydown', handleKeyPress);
document.body.classList.remove('full-screen-open');
};
// Here I get the warning: react-hooks/exhaustive-deps
// React Hook useEffect has a missing dependency: 'handleKeyPress'. Either include it or remove the dependency array.
}, []);
return (
// I also need handleKeyPress to bind it to this DIV here
<div
onKeyPress={handleKeyPress}
ref={divRef}
>
Content....
</div>
);
}
Essentially my effect is supposed to be a version of componentDidMount
, componentDidUnmount
, and it works, but the warning is there and I'd like to make sure I am using hooks correctly. I could just put eslint disable, but I don't like that solution, there has to be a right way to do this.