React Hooks: How to use useEffect()

download.png

What is Hooks?

Hooks were introduced in React version 16.8 and now used by many teams that use React. Hooks are mainly used in function-based components for the effective management of state. Technically every hook is a function. You can also create your own hook just by creating a function. Head-on to react documentation for more.

useEffect()

useEffect hook essentially is to allow side effects within the functional component.

So Now I am going to describe the basic form of useEffect Hook which we are going to use in our code. So whenever the content state will change , it will re-render the application and the useEffect function will run.

1_v0u1COhMO_sNksYremEsCw.png useEffect acts similarly to the methods componentDidMount(), componentDidUpdate(), and componentWillUnmount() in classes.

But !! By default, this code will run both after the first render and after every update. So, for every render, we are updating the title !

Beware when you're updating state from useEffect. it can create an endless loop of render & update!

  • ‘Ok, but I want to run this effect only when the component is mounted, not on every update’. Of course, you can do that.*

useEffect Dependency Array

useEffect has a second argument. Just to reiterate, the first argument is the callback that you are providing. So, the second argument is an array that tells React when to run this effect.

  • Render once

    to run something just when the component is rendered for the first time is using an empty array ( [ ] ) as a second argument for the useEffect call.

1_vPrsM-y6tef4JxVMWjMPNQ.png

  • Render on Update

This way the useEffect hook will only run if this variable changes.

1_NYIp_U1wNdwHAJY7cX01Gg.png In the above picture , useEffect will only run if ‘count’ changes.

This is a simple explanation of how an useEffect dependency array affects rendering. Hope this simple guide helps with learning the basics of the useEffect dependency array.