0

I realize a problem when using useState and useReducer hook that any lines of code after the update state function (setState, dispatch) will be called in the next re-rendering (with its previous state before update). It means that update state function causes re-rendering immediately and not waiting the whole function executed.

const [aaa, setAAA] = useState<boolean>(false);

const updateMyBiddingList = async (atDate?: string) => {
    try {
      console.log('step 0');
      const result = await getBiddingCartFromService(atDate ? atDate : myBiddingListState.myBiddingList[0].updatedAt);
      if (result.responseCode.toString().startsWith('2')) {
        setAAA(true);
        console.log('step 1');
      }
      console.log('step 2 ', aaa);
    }
    catch (err) {
      if (timeOut.current) clearTimeout(timeOut.current);
      timeOut.current = setTimeout(() => updateMyBiddingList(), TIMEOUT);
    }
  }

console.log('Component is re-rendering... ', aaa);

return ...

The above codes will log in the following order:

  • step 0
  • Component is re-rendering... true
  • step 1
  • step 2 true

Does anyone explain the workflow of update state hook for me? Thank in advance.

2 Answers 2

4

This is because React doesn't rely on an async task like that, there are two ways to simulate the result you want. One I'm going to call standard and one unstable version.

Unstable version

The first way is to wrap updates inside unstable_batchedUpdates callback. As the name suggests, this API will batch your updates in a single reconciliation pass, resulting in fewer component renders.

So the updated code will be something like:

import { unstable_batchedUpdates } from "react-dom";



const updateMyBiddingList = async (atDate?: string) => {
    try {
      console.log('step 0');
      const result = await getBiddingCartFromService(atDate ? atDate : myBiddingListState.myBiddingList[0].updatedAt);
      
      // Add unstable API where you cause re-render ⭐
      unstable_batchedUpdates(() => {
        if (result.responseCode.toString().startsWith('2')) {
          setAAA(true);
          console.log('step 1');
        }
        console.log('step 2 ', aaa);
      })
    }
    catch (err) {
      if (timeOut.current) clearTimeout(timeOut.current);
      timeOut.current = setTimeout(() => updateMyBiddingList(), TIMEOUT);
    }
  }

This will change the order of the logs to this

Component is re-rendering...  false
step 0 
step 1 
step 2  false
Component is re-rendering...  true

you can see code running with fake data from JSON placeholder in the following code sandbox.

codesandbox

Standard version (react common pattern)

It is not the only pattern you can do what you want, but it seems more react-ish like to me :)

  • you are requesting (an async action)
  • you want to change the state of the component that will cause re-render

this phase also change function definition for the very next render

  • you want to re-fetch on failure

I'm sticking to your implementation and don't want to split useEffect sections into tiny reusable parts, although it might be something you want to think about it.

The solution is to move your logic where it belongs, which means where you are going to call that function call in your dom tree.


// instead of aaa and setAAA :)
const [updated, setUpdated] = useState<boolean>(false)
const [hasError, setHasError] = useState<boolean>(false)
const timeOut = useRef<number>() 

useEffect(() => {
  const updateMyBiddingList = async (atDate?: string) => {
     try {
      console.log('step 0');
      const result = await getBiddingCartFromService(atDate ? atDate : myBiddingListState.myBiddingList[0].updatedAt);
      setHasError(false)
      if (result.responseCode.toString().startsWith('2')) {
        setUpdated(true);
        console.log('step 1');
      }
      console.log('step 2 ', updated);
    }
    catch (err) {
      setHasError(true)
      if (timeOut.current) clearTimeout(timeOut.current);
      timeOut.current = setTimeout(() => updateMyBiddingList(), TIMEOUT);
    }
  }
  if (!updated || hasError) updateMyBiddingList()

// timeOut.current can also be added here but it is not recommended
}, [updated, hasError])
1
  • Many thanks. That is what I want to understand. Also, your second way bring me something new that I haven't ever thought about it. What a great answer! Mar 22, 2021 at 10:09
2

Well that happens due to async logic of javascript. I think you're calling updateMyBiddingList function somewhere during render-phase, javascript starts it's process and since it's async react won't wait for it to finish. That would cause your application to freeze whenever you made an async request.

2
  • Sorry for late reply. I have done some experiments with this and I got one thing: If there is asynchronous function with update state hook functions in that, the update function will trigger re-render before executing next line of code. It means that the order I posted above is correct in api call (side effect) → I don't know whether it relates to pure function or not. I have tested update function in normal function such as onClickHandler for onClick event of button, everything is in order: step 0, step 1, step 2, trigger re-rendering. It's so weird. I haven't had an answer yet. Mar 17, 2021 at 3:36
  • I got something new, every function has await keyword for Promise function call will result in the weird order of update state hook functions (this function will trigger render before executing next lines) Mar 17, 2021 at 3:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.