useEffect is the hook you would need for handling side effects

useEffect is the hook you would need for handling side effects

Deal with side effects in your web app like a boss!

Hooks

  • Before learning about useEffect, it is essential to know what "React hooks" are because useEffect is one of those.
  • Hooks joined hands with React since version 16.8
  • Hooks let you to use the most important concepts of React like props, state, lifecycle, context, refs without using the Class Based Components
  • Classes in Javascript is a new feature since ES6. Classes are just a syntactic sugar over constructor functions & prototypical inheritance.
  • We will not be covering about the topics like Constructor functions, Prototypical inheritance in this article.
  • If you create a class and compile it in Babel , you can notice that the class will be converted into a constructor function
  • The main reason for using Classes in JS is just that they provide a clearer syntax to implement Inheritance.
  • For using classes, it would be good if the user has a good command on OOPS concepts.
  • So by eliminating classes and by barging the doors of reactjs with Hooks, one can use react comfortably without classes along with the most important features that one can use along with Classes

  • If you have used React before the year 2019, you would have definitely come accross the component life cycle methods like the componentDidMount, componentDidUpdate & componentWillUnmount while using the Class Based components

  • You can simply assume the useEffect hook as a combination of all of the three lifecycle methods.

Side Effects in React

  • Side effects or simply Effects are things like fetching data, manually changing something in the DOM. So, basically everything that happens in the application other than what React does is considered as a Side Effect.

Types of side effects in react

  • side effects that don't require any cleanup -> Network requests
  • side effects that require cleanup -> adding an event listener to the window.

Enough talking, let's take a look at 3 examples to understand how useEffect works.

Note : useEffect takes one obligatory argument & a second optional argument. In the following examples let us use a component called as Test

Case 1: The function inside of useEffect is called everytime, the component renders until it's unmounted

export default const Test = () => {
useEffect(()=> {
      console.log("executed everytime when the component renders")
})
return <h1>Test</h1>

}

Case 2: We will pass the second optional parameter now. It is an array & it is called as dependency array.

export default const Test = () => {
    const [number, setNumber] = useState(1);
    const [present, setPresent] = useState(true);

    useEffect(()=>{
      console.log("Executed whenever the value of **number** changes")
   },
      [number]
   })

//Note that the function is not executed only when the value of **present** changes

return (
   <h1>Test</h1>
)
}
  • It is important to know the role of this dependency array to fulfill the understanding of useEffect hook.
  • When the component re-renders everytime after the initial mount and the code comes past the useEffect hook, react will compare the current value of the elements in the dependency array with the previous value of the elements in the dependency array & if there is any difference in these values, then and only then react will execute the function inside of the useEffect hook. Otherwise, the function inside of the useEffect is not executed.

Case 3 : In this case, we will use a empty dependency array.

export default const Test = () => {
    const [number, setNumber] = useState(1);
    const [present, setPresent] = useState(true);

    useEffect(()=>{
      console.log("Executed whenever the value of **number** changes")
   },
      []
   })

//Note that the function is not executed only when the value of **present** changes

return (
   <h1>Test</h1>
)
}
  • Since, here the dependency array is an empty array, the component is rendered only once. I will explain to you how it works.
  • Earlier, I told you that during every re-render, the value of the dependency array is compared with the previous value of the dependency array.
  • Therefore, it is intuitive that when there are no elements in the dependency array, the dependency array of the current render compared with the dependency array of the previous array results in no change.
  • As a result of this, the function inside of the useEffect is called only once during the first render & it is untouched after mounting till it's unmounting phase.

Let's end this data transfer with an example that requires clean up of the side effect.

  • In this case, we will attach an event listener to the window, when the component is mounted.
  • This event listener is removed(clean up) and attached again when the component re-renders.

    eg :
    export default const Test = () => {
    const [value, setValue] = useState(0);
    
    useEffect(()=> {
      window.addEventListener("click", console.log("Click listener Added");
      return () => {
      window.removeEventListener("click", console.log("Click listener Removed");
    }
    })
    
    return (
     <h1>Test</h1>
    )
    }
    

Assume that the above component renders twice, then the console would look as below,

//for the first time when the component mounts
Click listener Added

//During the first re-render
Click listener Removed
Click listener Added

//During the second re-render
Click listener Removed
Click listener Added

//When the component is Unmounted
Click listener Removed

:-) This is my first blog. I enjoyed writing this because I had been using useEffect since a long time. But when I was writing this, I realised that my understanding of this hook was not up to the mark. I have learnt few things while writing this blog & I wish to continue writing blogs.

Please feel free to drop your suggestions on what areas I need improvement. Have a nice day (-: