23
What is useEffect()?, How does it work? & Why should we use useEffect()?
Prerequisite: Basic knowledge of React Js**
This blog covers about useEffect hook. What is the useEffect hook? How to use (Syntax)? How does it work? When to use it?, and some common use cases of useEffect hook.
Well, useEffect is React hook, which use to handle side effects functions (side Effects are those functions that interact with the outside world, or out of React Js ecosystem), and with useEffect, we can separate them into another Function.
It is like a Functional programming concept, where we try to encapsulate side effects in other functions so that other Functions can stay pure/unaffected.
useEffect hook must declare inside the component (top-level, don't declare them in the block), it will give several advantages (Thanks to closure):
useEffect(function sideEffect(){
.....
}, [dependencies_array_element])
- If you don't give dependences array, only pass the first argument, then useEffect runs whenever your component renders/re-renders.
- If you give an empty dependences array, then useEffect runs once(when your component renders the first time, after that, it will not run unless you refresh the page).
- If you give something in the dependencies array, then useEffect will run once by default after the component finish rendering. After that, whenever the value of elements in the dependences array change, then useEffect will run again. Example: [isItemHidden].
Well, whenever your components finish rendering, useEffects run unless you specified dependencies in the dependencies array.
Well, there are several cases where you should consider useEffects. Some of them are:
23