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

useEffect()-React Hooks(P2)

danijelajs profile image Danijela.js🛞 ・1 min read

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

Posted on by:

danijelajs profile

Danijela.js🛞

@danijelajs

FrontEnd developer React.js/JavaScript/CSS/HTML/ Redux/JQuery/Firebase/Next.js/Git/etc. 📩𝙙𝙖𝙣𝙞𝙟𝙚𝙡𝙖𝙛𝙪𝙚𝙠𝙀@𝙮𝙖𝙝𝙀𝙀.𝙘𝙀𝙢

Discussion

pic
Editor guide