React hooks: useEffect` why?

378 views Asked by At

Concerning the newly proposed https://reactjs.org/docs/hooks-reference.html#useeffect

  1. What are the advantages and use cases of the Effect hook (useEffect())?
  2. Why would it be preferable & how does it differ over componentDidMount/componentDidUpdate/componentWillUnmount (performance/readability)?

The documentation states that:


Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase).

but I think it was already common knowledge to have these behaviors in lifecycle methods like componentDidUpdate, etc. instead of the render method

There's also the mention that:


The function passed to useEffect will run after the render is committed to the screen.

but isn't that what componentDidMount & componentDidUpdate do anyways?

4

There are 4 answers

0
Pranta On

I think you can use functional component for literally everything. And even if you can't using traditional react, you can use some npm packages to achieve what you are trying to do. Moreover functional components are more organized and cleaner than the class components. I will bet my money on functional components.

0
vim kndll On

You can use both bro according to your situation But react hooks is quite complex than class
Better would be If u use hooks if you are not fresher .Its new than that of class component

0
Ibrahim shamma On

You can use it as long as you understand the main concepts behind the lifecycle

0
P.Zdravkov On

Contemporary React apps use PRIMARILY if not always, functional components and in some very very specific cases (or legacy code) class components which do offer explicit access to lifecycle methods such as componentDidMount, componentDidUnmount etc. News hooks like useLayoutEffect etc. are essentially substitutes to some of these lifecycle methods and are sufficient in 95% of the time, in my opinion.

The downsides of hooks typically is the dependency arrays which may sometimes require to further extract a value with another hook like useMemo which then can be checked statically, rather than using expressions in dep arrays - in fact this raises a warning.

But at the end of the day it really depends on what you want to implement and if you can find the right hook (a lot of times custom one) to suit your use case.