Handle the lifecycle component methods in functional component using React useEffect Hook

What is useEffect : 

In our application, we required to call network operations, subscription for the events, etc. The useEffect provides you a way to handle that operation using hooks.

The useEffect is a combination of lifecycle methods of the react component and provides you a better way to handle those events. The useEffect is a combination of lifecycle methods componentDidMount, componentDidUpdate, and componentWillUnmount.

Now, let's start with how can we define and use the useEffect in react-native.

Syntax of useEffect 
To use the useEffect you required to import it from the react package.

import React, { useState, useEffect } from 'react';

useEffect(()=>{
})

or 

React.useEffect(()=>{
})

How useEffect works?

The useEffect is called after every render.  After the first render takes the place the useEffect will be call and perform the operations. It will affect the performance of the application but we have some ways using which we can customize the call of the useEffect so that it will not down the performance of the application. 

There is some effect which is fire and forgot means we do not have to unsubscribe or clean the effect for example network call etc. But we also have the effect which we have to clean up once the component is unmounted.

Cleanup or Unsubscribe the event

In a simple component, we have to override the componentWillUnmount method and put all the cleanup code there. In this some-time, it happens that we forgot to write the clean up code while implementing the functionality.

useEffect provides an easy way to handle that. You write the code in the useEffect and after that the effect will clear when the component will unmount. The useEffect will take care to clear the subscription for you. 

Let's see with an example.

useEffect(()=>{
 // subscribe the event here

  return () => {
     // Unsubscribe the event here
  }
})


Inject the dependencies for useEffect

If you want to call the useEffect after the change of state then you can pass the state as a dependency for that useEffect while defining it. Once the state value is changed the react-native automatically detect the affected useEffect and triggered that for you.

Let's have an example :

useEffect(() => {
     fetchDataAsPerPage(page)
 }, [page]);

You can also pass the multiple 
dependencies by a comma-separated value

useEffect(() => {
     fetchDataAsPerPage(page)
 }, [page,...]);

Comments