Home > other >  React, wait for a hook to finish before starting another hook
React, wait for a hook to finish before starting another hook

Time:02-23

I have a component like follows

export const Component = () => {
  const { data: item} = useItem();
  const { list } = useItemList(item?.id.toString());


  return(
    item ? (<p>some stuff</p>) : (<p>loading</p>)
  )
}

Problem is the app is not waiting for item to be available and it runs useItemList while its undefined, but i've to wait to fetch item

How can I solve so?

CodePudding user response:

you cannot run the hook conditionally because React relies on the order in which Hooks are called

React cannot track the state correctly if a hook is skipped

An easy solution is to modify your useItemList code, if the argument is undefined, then don't call whatever is inside it.

update: my solution is incorrect because the hook value is initial value, so it wont work.

this is the correct solution:

You should return a memorized callback from useItemList instead and run this callback in useEffect with item and that callback(optional) as dependency

  • Related