Search code examples
javascriptreactjsreact-hooksuse-effect

what is the difference between using useEffect inside a custom hook and a component


I want to know the difference b/w using useEffect hook in a component and a custom hook.

For example

If i have a functional component (Component) and directly use useEffect hook inside it

import React,{useEffect} from 'react';

function Component(){
   useEffect(()=>{
       //some code                     //callback fires after component renders
   },)

   return (<div>Component</div>)

}

if a create a custom hook (useCustomHook)

import React,{useEffect} from 'react';
function useCustomHook(){
   useEffect(()=>{
      //some code     //this callback also get fired after component renders
    })
}

Now if i use this custom hook inside Component

import useCustomHook from 'customhook';
import React,{useEffect} from 'react';
function Component(){

   useCustomHook();

    return(<div>Component</div>)

}

I want to know

Is the useEffect hook related to the Component, so that it's callback only run after the Component renders, because In using useCustomHook it was declared outside of the Component i.e it was inside the custom hook, but then also the callback get's called only after the Component renders,

So is there any relation b/w useEffect and Component, So that the callback of useEffect get's called only after Component renders, no matter wheter the useEffect is declared inside or outside of the Component i.e (useCustomHook)


Solution

  • Unless the custom hook is invoked the logic inside it will not be evaluated and hence regardless of what hook you define inside of it, those are not run at the time of definition

    The useEffect function inside custom hook will only run when you use it inside a functional component and invoke it. Also note that the behavior of useEffect will remain exactly the same as if it were written inside the functional component itself