Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React 18 strict mode causing component to render twice [duplicate]

The changes to strict-mode in React version 18 causes my code to render twice, which causes an error in axios abort controller, but I don't know how to clear the error from the browser console after the app renders twice.

Please note: I am working on a sign-up / log-in app and even after I successfully logged in, React takes me back to the log-in page, because of the axios error

useEffect(() => {
    let isMounted = true;
    // used by axios to cancel request
    const controller = new AbortController();

    const getGoals = async () => {
        try {
            const response = await goalPrivate.get("/goals", {
                // option to cancel request
                signal: controller.signal
            })
            console.log(response?.data);
            // set goals state when component mounts
            isMounted && setGoals(response?.data);
        } catch (error) {
            console.log(error.message);
            // when refreshToken expires
            navigate("/login", { state: { from: location }, replace: true });
        }
    }

    getGoals();

    // cleanup function
    return () => {
        // don't set state if component unmounts
        isMounted = false;
        // cancel request if component unmounts
        controller.abort();
    }
    
    // eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
like image 453
Ifeanyi Chima Avatar asked Sep 08 '25 09:09

Ifeanyi Chima


1 Answers

React StrictMode calls all Effects twice to make sure their cleanup/unmount handlers work as intended. You may need to change your effects accordingly, even if they have an empty dependency list and would normally not unmount before the site is closed.

Note, this only happens in Strict + development mode. In a production build, effects will only be called once and when their dependencies change.

Fore more context, see https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state

like image 57
DustInComp Avatar answered Sep 10 '25 04:09

DustInComp