I have a registration page that will report back to the index when the operation was successful. Thet communication, as of right now, is happening through query params.
const Foo: React.FC = () => {
const router = useRouter();
const [useModal, setUseModal] = useState(false);
const closeModal = () => {
setUseModal(false);
};
const generateModalContent = (queryContent: ParsedUrlQuery) => {
if (Object.keys(queryContent).length !== 0) {
return {
//key-values from query
};
}
};
const modalContent = generateModalContent(router.query);
if (Object.keys(modalContent!).length !== 0 && useModal === false) {
setUseModal(true);
}
return (
<>
//unrelated stuff
{useModal ? <ModalNotification {...modalContent} /> : null}
</>
);
};
Problem is that every time closeModal is called to close the modal, it is shown again since, upon re-render, the query is still there and the cycle will repeat. I'm looking for a clean way to display the data sent by query once, and upon the user closing the modal it doesn't show up again.
To avoid calling that part of your code in every re-render you must wrap it in a useEffect with the correct dependencies like so:
React.useEffect(() => {
const modalContent = generateModalContent(router.query);
if (Object.keys(modalContent!).length !== 0 && useModal === false) {
setUseModal(true);
}
}, [router]);
That way it will only execute when router changes and not in an infinite cycle.
You can read more about it in the React docs.