I have a component called categories.js which will be called in App.js, there is a useEffect in categories.js as the following
useEffect(() => {
const fetchCategories = async () => {
console.log('fetchCategories');
try {
const response = await apiClient.get('/category/group');
console.log(response.data.data);
setCategories(response.data.data);
} catch (error) {
console.log(error);
}
};
fetchCategories();
console.log('use effect 123');
}, []);
in the return section, i have a browser router like this
return (
<div>
<Routes>
<Route path="/posts/:postId/page/:page" element={<OpenPostsOverlayByRoute />} />
</Routes>
{Object.keys(categories).map((group) => (
....
here is a OpenPostsOverlayByRoute element also in categories.js
const OpenPostsOverlayByRoute = () => {
const { postId, page } = useParams();
console.log('OpenPostsOverlayByRoute: ' + postId);
/*useEffect(() => {
// Update the state using the provided setter
setRoutePostId(postId);
console.log('OpenPostsOverlayByRoute: ' + postId);
}, [postId);*/
}
when i access the page https://localhost:3000/posts/235/page/2, it will print OpenPostsOverlayByRoute 235 twice, do anyone know how to handle this situation?
——————temp solution—————
in return section:
<Routes>
<Route path="/posts/:postId/page/:page" element={<OpenPostsOverlayByRoute setIsRoute={setIsRoute} />} />
</Routes>
in use effect:
setIsRoute(2);
in OpenPostsOverlayByRoute
if (isRoute == 1) {
}
2
Answers
In your code, the first time component will render, so it will give console, and then again, you’re calling an API in useEffect and changing the parent state, so child component will get re-rendered, that’s why console is output twice.
Hope this helps!
This is expected behavior in development mode
https://react.dev/reference/react/useEffect#my-effect-runs-twice-when-the-component-mounts
The reason for this is to help with debugging.