1

I know I can't directly pass an async callback like this to useEffect

  useEffect(async () => { // not supported, as this implicitly returns a Promise
    const result = await axios(
      'https://someurl',
    );
 
    setData(result.data);
  });

as React expects nothing or a (cleanup) function callback as the first parameter for useEffect.

What I don't understand though: Is there any specific reason for this design choice? Why isn't there instead a signature like useEffect(callback, cleanup, dependencies) which would then allow me to directly pass in an async callback as first parameter, as the cleanup function could be easily passed in as second parameter?

stefan.at.kotlin
  • 15,347
  • 38
  • 147
  • 270

1 Answers1

2

What I don't understand though: Is there any specific reason for this design choice?

One of the reasons that comes to mind is following. In react often when you return function from useEffect it does job like unsubscribing from things etc. and often you might need to access some variables from useEffect. For example:

  useEffect(() => {

    let cancelled = false;
    fakeFetch(person).then(data => {
        if (!cancelled) {
            setData(data);
        }
    });

    return () => {

        cancelled = true;

    }

 }, [person])

With your design, you wouldn't be able to do above.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90