Search code examples
javascriptreactjsmern

useEffect calls stop working when called too many times. Why?


I have a useEffect, which works properly when done like this.

    async function readUserPosts(profileID){
        try {
            const res = await axios.post(...);
            setUserPosts(res.data.posts);
        } catch (err) {
            console.error(err);
        }
    }

    useEffect(() => {
        readUserPosts(profileID);   
    }, [profileID])

But, if I define the same useEffect by adding a second function like this:

    async function readUserPosts(profileID){
        try {
            const res = await axios.post(...);
            setUserPosts(res.data.posts);
        } catch (err) {
            console.error(err);
        }
    }

    useEffect(() => {
        readUserPosts(profileID);
        functionX();
    }, [profileID])

The useEffect works the first few times I reload the page, after which it stops working. I do not get any error message, even when I wrap the try catch around the 2 functions. FunctionX is a simple async function. I have substituted other test functions on functionX, and it produces the same result. So basically, it will not work when a second function is defined. What went wrong?


Solution

  • Enclose the two methods with useCallback. Here is one method for example:

    const readUserPosts = useCallback(async function() {
      try {
            const res = await axios.post(...);
            setUserPosts(res.data.posts);
        } catch (err) {
            console.error(err);
        }
     }, []);
    

    And try with adding dependency like this:

    useEffect(() => {
        readUserPosts(profileID);
        functionX();
    }, [profileID, readUserPosts, functionX])