Currently, I have implemented a useEffect
function within the Layout
component. This function is responsible for fetching my userData
and storing it in the redux-store
. However, I have noticed that this function gets triggered every time there is a route change.
I would like the useEffect
function to only run the first time and avoid triggering again when the routes are changed. This continuous triggering is resulting in unnecessary requests being sent to the server. How can I prevent this from happening?
Below is the code snippet of my Layout
component:
import { useEffect, useState } from "react";
import Navbar from "../navbar/navbar";
import Footer from "../footer/footer";
import Head from "next/head";
import { useCookies } from "react-cookie";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { getUserData } from "../../redux/actions/Auth";
const Layout = ({ children }) => {
const [cookie, setCookie] = useCookies(["token"]);
const dispatch = useDispatch();
useEffect(() => { // Issue: useEffect triggers on each route change
const { token } = cookie;
if (token) {
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
dispatch({ type: "IS_LOGGED_IN" });
dispatch(getUserData(token));
}
}, []);
return (
<div className="layout" dir="rtl">
<Head>
<meta name="description" content="" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link
rel="preconnect"
href="https://fonts.gstatic.com"
crossOrigin="true"
/>
<link
href="https://fonts.googleapis.com/css2?family=Noto+Kufi+Arabic:wght@100;200;300;400;500;600;700;800;900&display=swap"
rel="stylesheet"
/>
<link
rel="stylesheet"
type="text/css"
charset="UTF-8"
href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.css"
/>
<link
rel="stylesheet"
type="text/css"
href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick-theme.min.css"
/>
</Head>
<Navbar />
{children}
<Footer />
</div>
);
};
export default Layout;