I have a react functional component and I want to run some code in every render .
You know useEffect
hook without dependency array runs every time on render.
heres the code
function Component({a, b}){
useEffect(()=>{
console.log('component rerenderd')
// some code here
})
return(
<div>
Some content
</div>
)
}
on the other hand without useEffect doing same thing
function Component2({a, b}){
console.log('component rerenderd')
// some code here
return(
<div>
Some content
</div>
)
}
My question is what is the difference between both of them ?
useEffect(callback, dependencies) is the hook that manages the side-effects in functional components. callback argument is a function to put the side-effect logic. dependencies is a list of dependencies of your side-effect: being props or state values.
The motivation behind the introduction of useEffect Hook is to eliminate the side-effects of using class-based components.
What does useEffect do? By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we'll refer to it as our “effect”), and call it later after performing the DOM updates.
The useEffect Hook allows you to perform side effects in your components. Some examples of side effects are: fetching data, directly updating the DOM, and timers. useEffect accepts two arguments.
useEffect
callbacks executed after the render phase which is the main difference between the two.
See the next example:
// Log order:
// "executed at render phase"
// "executed after render phase"
const App = () => {
useEffect(() => {
console.log("executed after render phase");
});
console.log("executed at render phase");
return <></>;
};
Read more here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With