React JS | useEffect Hook

CodeyMaze
3 min readMar 5, 2022

--

useEffect() is a react hook that lets you perform side-effects in functional components. It serves the purpose of three lifecycle methods from class components.

These lifecycle methods are componentDidMount(), componentDidUpdate() and componentWillUnmount(). It means we can use useEffect() when some code to be executed when component mounts, whenever component re-renders & when the component is unmounted.

useEffect() will accept one callback function and one optional parameter. If we call useEffect() without any optional parameter then this callback function is going to execute every time component re-renders

The syntax of useEffect is like this -

useEffect(() => { // call back function }, [ // Optional set of dependencies here] )

Let’s take simple example of useEffect -

As you can see in the above example, when message updated from text box, component re-renders and on each render useEffect() gets executed.

We can optionally pass an array of dependencies as second parameter. In this case, the useEffect() callback function will get executed only if any of the dependencies changes in the given dependencies array.

Let’s take one more textbox that sets the document title. Here we have passed message as second parameter which means useEffect callback function gets executed at component mount and when message updates.

Now let’s pass blank array as second parameter.

As you see in the above example we have passed [] empty array as second paramter to useEffect() function. Executing this code will call the useEffect() callback function only at initial render that is on mounting of component. If message updates useEffect() does not gets called again. In this way we can call an API to fetch some data in useEffect callback.

We can execute callback function when component gets unmounted with the help of useEffect(). If we return a function from useEffect() callback method this function will execute when component gets unmounted.

This can be useful in case if we have to do some cleanup task like cleanup data to free memory or to remove event listeners.

As you can see in this example we return a function from useEffect callback and its going to remove the event listener that we set at component mount.

Subscribe to our Youtube channel for more videos :

https://www.youtube.com/channel/UCEXWe9R6-ppk4zhNo2JbtmQ

--

--

CodeyMaze
CodeyMaze

Written by CodeyMaze

Crafting Solutions Through Code & Words https://codeymaze.com Feel free to follow me :)

No responses yet