DEV Community

Cover image for useEffect()-React Hooks(P2)

Posted on

useEffect()-React Hooks(P2)


  • 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


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

Top comments (0)