User talk:Nink

From Izara Wiki
Jump to navigation Jump to search

useEffect: Render Cycle and Cleanup Function

In the sitePageConfigOutput, there're two useEffects to be used which pulls two different response data from the backend.

 useEffect(() => {
   // let cancel = false;
   async function sendRequestA(objectFormConfigId) {
     let responseDataA = await sendBackendRequestA(
       "post",
       "https://0yzv0v3f86.execute-api.us-west-2.amazonaws.com/Test/Email/List",
       {
         objectFormConfigId: objectFormConfigId,
       }
     );
     cancel = false;
     if (cancel === false) {
       setObjectFormConfig((objectFormConfig) => {
         objectFormConfig.objectFormConfigId = responseDataA;
         return { ...objectFormConfig };
       });
     }
   }
   sendRequestA(getObjectFormConfig);
   return () => {
     cancel = true
   };
 }, [getObjectFormConfig]);

Problems

  • useEffect returns the clean up function before the effect
  • If condition renders only once instead of four times

Possible causes

  • Due to the async function, useEffect has to skip the async function and push it into the update queue, so there’ll be four sendRequestA in the queue waiting to be rendered. While waiting, useEffect will return the cleanup function.
  • useEffect remembers the last value, then renders the tasks in the queue. Therefore, for index 0 to 2, cancel will be set to true (due to the cleanup) and to false for the last index (3).

Solution

  • Set cancel to false right before the if condition.

Note

The reason why the last index doesn’t clean up after finishing the effect is still unknown. It might happen because all the tasks are done, so there’s no need to clean up anymore. However, the cleanup function runs when a component unmounts and after each (re-)render. Therefore, the last index still needs the cleanup.

Resources