reactjsreact-suspense

Idiomatic way to track if Suspense finish


Example:

  <Suspense fallback={<ClearLoading />}>
    // stuff
  </Suspense>

To track if the whole suspense node finishes loading, I put an effect cleanup in <ClearLoading> like this:

const ClearLoading = () => {
  useEffect(() => {
    return () => {
      // Do sth when suspense finish
    }
  }, []);

  return null;
};

This seems stupid. What is the generally accepted way of doing this?


Solution

  • Using useEffect is the idiomatic approach, as mentioned in React 18 upgrade guide.

    However, by moving it to an empty child component of Suspense, you wont need a wrapper for every Loading component.

    <Suspense fallback={<Loading/>}>
        <PullTheLever/>
        // stuff
    </Suspense>
    

    The tracking-component doesnt need a return value.

    function PullTheLever() {
        useEffect(() => {
            // Do sth when suspense finish
        }, []);
    
        return null;
    }