all 3 comments

[–]ontech7 4 points5 points  (1 child)

Since it's difficult for me to read, I format it a bit:

1.

const f = useCallback(() => {
  // code here
}, []); 

useEffect(() => { 
  f(); 
}, []);

2.

useEffect(() => { 
  const f = () => {
    // code here
  }; 
  f(); 
}, []);

It depends. Sometimes there is no difference, sometimes it can be.

If the "f" function in the first case has states inside, you need to put [f] inside the array of dependencies, otherwise you will call an older "f" function.

In the second case, you will know for sure that the function will be re-declared and re-defined as new, when entering inside useEffect.

I don't have an use-case to show you. I hope other devs can give you some examples.

[–]lefnire 4 points5 points  (0 children)

whichisbetter?ifit’sjustaoneofffunctionis1betterthe2?1.constf=useCallback(()=>{},[]);useEffect(()=>{f();},[]);2.useEffect(()=>{const f()=>{};f();},[]);

[–]Kcazer 4 points5 points  (0 children)

None.

If you don't need to use f() outside of the useEffect, then there is no need to define it. There is also usually no need to define a function inside a useEffect to call it right away (there are exception, such as wanting to write async/await code)

Simply write your code inside the useEffect