DEV Community

kk1123
kk1123

Posted on

useEffect must not return anything besides a function, which is used for clean-up.

  1. This mistake is caused by returning something in the useEffect function.

  2. Can only return nothing or a clean-up function in useEffect function:

Wrong usage:

 useEffect(()=>getData(),[])

  async function getData() {
    const url = "http://localhost:8080/hello";
    try {
      const response = await fetch(url);
      setData(response)
    } catch (error) {}
  }
Enter fullscreen mode Exit fullscreen mode
  1. getData returns a promise because it is declared to be async. This promise will eventually be resolved when asynchronous operations (like fetch) complete.

  2. Cannot return a promise in useEffect function. Only return nothing or the clean-up function.

Correct usage: write asynchronous functions in useEffect and call them so that the useEffect function returns nothing.

useEffect(() => {
    async function getData() {
      const url = "http://localhost:8080/hello";
      try {
        const response = await fetch(url);
        setData(response);
      } catch (error) {}
    }
    getData();
  }, []);
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay