1

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;
3
  • 5
    Are you using <StrictMode>? If so, this is the expected behavior. In dev builds, strict mode will simulate unmounting and remounting the component so you can more easily catch bugs related to not tearing down your effects. reactjs.org/docs/strict-mode.html#ensuring-reusable-state Commented Aug 13, 2022 at 9:59
  • I agree here with @NicholasTower, maybe u are using the <StrictMode>. Commented Aug 13, 2022 at 10:06
  • Yes, I was using Strict mode Commented Aug 13, 2022 at 10:21

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.