DEV Community

Discussion on: 6 use cases of the useEffect ReactJS hook

Collapse
 
mrfacundo profile image
Facundo Troitero • Edited

On the first case, "fetch API data", why not just fetchData? What's the use of useEffect?

        const fetchData = async () => {
            const response = await fetch('https://swapi.dev/api/people/1/');
            const data = await response.json();
            console.log(data);
            setBio(data);
        };
        fetchData();
Enter fullscreen mode Exit fullscreen mode

fetchData will be run and data will be provided to the return part of the component. However, I tried that and it results in a loop, the component keeps fetching data. Why?

On the second case, "validating input field", why not just validate inside of the inputHandler like this?

    const inputHandler = e => {
        setInput(e.target.value);
        if (input.length < 5 || /\d/.test(input)) {
          setIsValid(false);
      } else {
          setIsValid(true);
      }
    };
Enter fullscreen mode Exit fullscreen mode

this seems to work, what's the use of useEffect here?