React lifecycle hooks in functional component

React lifecycle hooks in functional component

Beginners guide to reactjs lifecycle hooks in functional components.

Fazail Alam
Frontend dev · Tue Aug 30 2022

Reactjs is javascript library to handle the UI aspect of your web application. It is open source and is maintained by Facebook(Meta).

On component mount

There will be situation when you want to do something when your component first mount. Something like calling an Api, conditionally rendering something, or any other thing according to your use case. In this situation we can use react’s useEffect hook.

import { useEffect } from 'react';

export default function SomeComponent(){

	useEffect(()=>{

	},[])  

	...
} 

Note i’m passing an empty array next to callback function, this will ensure that our useEffect hook will only run once.

On Component update

Of course you need to keep track when a component updated to handle some other tasks in your application. So to do that just pass the variables that you want to keep track inside the useEffect array. Whenever the passed variables changes useEffect will run.

import { useEffect,useState } from 'react';

export default function SomeComponent(){
	const [show,setShow] = useState(false);
	useEffect(()=>{
		// do something
	},[show, /* any other variables */])  

	...
} 

In the above code whenever show is changed that useEffect will execute.

On Component unmount

Lets say you have some heavy api calls in your useEffect that is running but user suddenly move to a different page, will your api call will still be running or stop executing?

The answer is Api will still be running till it completes its network calls. So to deal with this kind of situation we need to handle these in useEffect return function.

import { useEffect,useState } from 'react';

export default function SomeComponent(){
	const [show,setShow] = useState(false);
	useEffect(()=>{
 
		fetch('https://some-api');

		return ()=>{
			// abort your api request here
		}

	},[show, /* any other variables */])  

	...
} 

In that return function you can do something according to your use cases on component unmount.

On any state update

You may be wondering how can i do something whenever any of the state changes in that functional component. Well answer is simple just do not pass any array to useEffect hook.

import { useEffect } from 'react';

export default function SomeComponent(){

	useEffect(()=>{

	})  

	...
} 

This will run every time any of state changes.

That its for this article i hope you have understood lifecycle in functional components.

Want frameworks news and updates?

Sign up for our newsletter to stay up to date.

Share on: