简体   繁体   中英

useEffect without dependencies in react component executes twice

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;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM