Let's understand useEffect()

Let's understand useEffect()

Look up for useEffect

Let’s understand how useeffect works

Understanding syntax of useEffect

useEffect(<callBackFunction>,<dependency array>)

What should be there in callBackFunction?

All side effects should go inside callBackFunctions, like API call , some calculation which doesn't effect output

What is dependency array?

This array tells the useEffect when to execute callBackFunction

When does useEffect is called ?

At the first component is mounted (here mounted meaning is your HTML code inside return is added to DOM tree)and then useEffect is called.

Proof of it :

If you try to access any ref created using useRef() outside useEffect() before component Mounted you get undefined where inside useEffect() it gives the ref pointed to one of the element

Let's understand its behaviour

SyntaxdescriptionHow it worksis it called on state update?
useEffect(()⇒{})useEffect without dependencyit is called every time the component rendersyes
useEffect(()⇒{ return()⇒{ } })useEffect without dependency with return addedit is called every time and every time return is executed to clean up previous values. First return function is executed then the body of the function inside useEffect is called or executedyes
useEffect(()⇒{},[])useEffect with empty dependency arrayit is called only once, that is the time of the first render and in consecutive renders, it is not calledno
useEffect(()⇒{},[<somevariable>])useEffect with dependency array with valueit is executed whenever there is a change in the value of a dependent variable.depends on the variable you pass

How does useeffect behave with a dependency array with value?

1. Objects ⇒ as state variables are immutable they always create new objects even if the values are the same. Thus when compared inside the dependency array it will be the new one, hence it executes the function
2. primitive values ⇒ primitive values are considered as the same value not reference, hence updating the state value or dependent variable to the same value doesn’t makes the useEffect to execute the function

Here is the code link to work around
https://codesandbox.io/s/xenodochial-architecture-v3mcz7?file=/src/App.js

That's the wrap, if you have any comments or want to add-on feel free to add-on

Say Hi to me on Twitter and LinkedIn