Reputation: 688
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)
Upvotes: 4
Views: 1399
Reputation: 557
Suppose inside the functional component you have written 3 effects. You also have 2 custom hooks that have 1 effect each. So when you use these custom hooks inside your functional component you can imagine that now there are a total of 5 effects inside your functional component who's callback function will be invoked when the condition will meet after the component is being rendered.
Effects defined inside the functional components runs after the component is rendered and the browser in painted. React also guarantees that all the effects will run before the next render. But the order in which effect's callback function will be invoked depends totally on the amount of time taken to execute it.
Here is the link to a code sandBox explaining my point https://codesandbox.io/s/adoring-murdock-5ifil?file=/src/useTry.js
Upvotes: 0
Reputation: 281686
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
Upvotes: 2