I have a functional component where if I have some error calling an API I want to open a Modal showing that error. The property who decides if this modal is open is stored using context API. So I had this code in the component:
const modalContext = useContext(ModalContext);
useEffect(() => {
if (error !== "") {
modalContext.showModal();
}
}, [error]);
But I have this warning:
React Hook useEffect has a missing dependency: 'modalContext'. Either include it or remove the dependency array react-hooks/exhaustive-deps
I read that to fix this issue I can use refs, so I changed the code and now I have:
const modalContextRef = React.useRef(false);
modalContextRef.current = useContext(ModalContext);
useEffect(() => {
if (error !== "") {
modalContextRef.current.showModal();
}
}, [error]);
I wonder if this is the correct way to proceed or if it's a bad practice.
Thanks!