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 :)

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

๐Ÿ‘‹ Kindness is contagious

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

Okay