Home > Web Front-end > JS Tutorial > useEffect must not return anything besides a function, which is used for clean-up.

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

Patricia Arquette
Release: 2025-01-05 10:40:40
Original
461 people have browsed it

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) {}
  }
Copy after login
  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();
  }, []);
Copy after login

The above is the detailed content of useEffect must not return anything besides a function, which is used for clean-up.. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template