Home > OS >  useEffect without dependencies in react component executes twice
useEffect without dependencies in react component executes twice

Time:08-13

Hello I have a problem with useEffect. It is without dependencies because I want to execute this only once. I'm also using react router v6. But the useEffect in Profiles.js component runs twice and I don't know how to fix it. Below it is the App component which is the parent of Profile and the Profile component which is the problem.

App.js:

function App() {
return (
    <div>
        <Navbar />
        <Routes>
            <Route
                element={<Navigate replace={true} to={"/welcome"} />}
                path="/"
            />
            <Route element={<Profiles />} path={`/profiles`} exact />
            <Route element={<LandingPage />} path={"/welcome"} />
            <Route element={<Main />} path={"/main"} />
            <Route element={<MyProfile />} path={"/myprofile"} />
        </Routes>
    </div>
);
}

export default App;

Profiles.js:

const Profiles = (props) => {
const [profiles, setProfiles] = useState([]);

useEffect(() => {
    const fetchProfiles = async () => {
        console.log("profiles");
        // const snapshot = await get(ref(database, `users/`));
        // if (snapshot.exists()) {
        //     const response = snapshot.val();
        //     for (const uid in response) {
        //         if (uid !== user.uid) {
        //             setProfiles((prevState) => {
        //                 return [response[uid], ...prevState];
        //             });
        //         }
        //     }
        // }
    };
}, []);
return (
    <div>
        <ProfileRecommendation />
    </div>
);
};

export default Profiles;

CodePudding user response:

You most likely have <React.StrictMode/> enabled (Somewhere you are wrapping your application in <React.StrictMode/>). This behaviour will only occur on the development environment (meaning that on production useEffect will run only once). If you do not want that behaviour on your development environment then remove the <React.StrictMode/> wrapper.

You can read more about StrictMode here: https://reactjs.org/docs/strict-mode.html

CodePudding user response:

in development mode usseefect run twice beacuse of strictmode , bulid your project you can see it works as you perform.

  • Related