Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between with and without useEffect in react functional component

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 ?

like image 269
user13103887 Avatar asked Jun 30 '20 08:06

user13103887


People also ask

Can I use useEffect in functional component?

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.

What is the benefit of useEffect?

The motivation behind the introduction of useEffect Hook is to eliminate the side-effects of using class-based components.

What is the purpose of useEffect function?

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.

What is the purpose of using useEffect hook?

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.


1 Answers

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 <></>;
};

Edit useEffect execute phase

Read more here

like image 153
Dennis Vash Avatar answered Oct 08 '22 02:10

Dennis Vash