search

Home  >  Q&A  >  body text

What cleanup functions can be used with this useEffect hook?

I can't figure out what cleanup function to apply in this useEffect hook. It works fine without the cleanup function.

useEffect(() => {
            const fetchProfileUser = async () => {
                if (profileUserId === existingUser._id) {
                    setprofileUser(existingUser);
                } else {
                    const profileUser = await UserApi.getUser(profileUserId);
                    setprofileUser(profileUser);
                }
            };
            fetchProfileUser();
        });

P粉364642019P粉364642019440 days ago523

reply all(1)I'll reply

  • P粉471207302

    P粉4712073022023-09-16 14:32:52

    You don't always need a cleanup function. But most of the time, in useEffect you need a dependency array, even if it is empty. If you're doing requests, you definitely need a dependency array.

    If you are making a request, you can use AbortController to cancel the request and use the cleanup function if the component is uninstalled.

    reply
    0
  • Cancelreply