React useEffect

According to definition by React Effect Hook lets you perform side effects in function components.  It helps in adding componentDidUpdate and componentDidMount combined life cycle in React’s functional component. To use this we need to first import it from react.

import React, { useEffect } from ‘react’;

const tutorials=(props)=>{

   useEffect( ()=>{

      console.log(‘hello’);

      setTimeout( ()=>{ alert(‘hello’); }, 2000);

   });

}

When you run it you will see console log and alert every time you render it. You can call http request inside useEffect. You can make it work like componentDidMount by passing empty array as an argument.

const tutorials=(props)=>{

   useEffect( ()=>{

      console.log(‘hello’);

      setTimeout( ()=>{ alert(‘hello’); }, 2000);

   }, [] );

}

As shown above you can pass multiple elements inside the array. To do the cleanup work in the functional component add a return statement inside useEffect at the end of function call which will return a function. This function will perform the cleanup work. Frequency of the cleanup work excecution will depend on the second argument passed to useEffect function.

import React, { useEffect } from ‘react’;

const tutorials=(props)=>{

   useEffect( ()=>{

      console.log(‘hello’);

      setTimeout( ()=>{ alert(‘hello’); }, 2000);

      return ( ()=>{

         console.log(‘cleanup on change of player props’);

      });

   }, [props.player]);

}