Home > Mobile >  react-useEffect execution time
react-useEffect execution time

Time:09-12

i'm woundring if is it OK to write all the logic inside a useEffect react hook or to create a function and call it inside the useEffect.

First way

 useEffect(()=>{
// code logic 
},[dependency array])

Second way:

const toDoFunc = ()=>{
// code logic
}

useEffect(()=>{
toDoFunc()
},[dependency array])

i'm really confused cause i tested both approaches in matter of time execution(using the console.time && console.timeEnd functions ) and found that sometimes the first approache is faster and sometimes the second one is faster.

CodePudding user response:

There is no significant difference in terms of performance. If your function is only used inside your useEffect you should place it there. Otherwise you would need to declare the function as a dependency and stabilize its reference, or use the upcoming useEvent hook. If your function is not reactive, you could also put it outside the component.

  • Related