skip to Main Content

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


  1. 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!

    Login or Signup to reply.
  2. 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.

    To help you find bugs, in development React runs setup and cleanup one extra time before the setup. This is a stress-test that verifies your Effect’s logic is implemented correctly. If this causes visible issues, your cleanup function is missing some logic. The cleanup function should stop or undo whatever the setup function was doing. The rule of thumb is that the user shouldn’t be able to distinguish between the setup being called once (as in production) and a setup → cleanup → setup sequence (as in development). See common solutions.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search