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
Syntax | description | How it works | is it called on state update? | |
useEffect(()⇒{}) | useEffect without dependency | it is called every time the component renders | yes | |
useEffect(()⇒{ return()⇒{ } }) | useEffect without dependency with return added | it 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 executed | yes | |
useEffect(()⇒{},[]) | useEffect with empty dependency array | it is called only once, that is the time of the first render and in consecutive renders, it is not called | no | |
useEffect(()⇒{},[<somevariable>]) | useEffect with dependency array with value | it 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