DEV Community

Cover image for useEffect()-React Hooks(P2)
Danijela.js๐Ÿ›ธ
Danijela.js๐Ÿ›ธ

Posted on

6 4

useEffect()-React Hooks(P2)

useEffect()

  • It's similar to componentDidMount(), componentDidUpdate() and componentWillUnmount().
  • It's called everytime the component is rendered or re-rendered.
  • You can have as many useEffects as you want.
  • Multiple useEffect() will fire off in order, one after the other
  • Some side effects require a cleanup, some don't.

Now, lets take a look at an example:

Alt Text

Explanation:

As you can see, we have a variable called button, and a function getFact, that updates that variable.

We are using the useEffect() hook to fetch date from some random API.

First we are fetching the data, then we have a cleanup function. It's "cleaning up" the previous function by displaying "Loading..." in an h2 tag.

-As I mentioned, not every side effect needs a cleanup

We have an array [button] as the second argument, so the useEffect() will be called just when the variable button is changed.

And at the end we have a button with a onClick event, where getFact function updates the state of the button variable. Which triggers the useEffect() hook.

Here is the end result:

Alt text of image

I hope you enjoyed this little tutorial :)

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your appโ€™s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free โ†’

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay