React Hooks

#day6learningReact

Introduction:

Understanding useEffect hook: useEffect is an in-built React hook that allows actions to synchronize with the external environment.

Component LifeCycle Status:

  1. Initialization: The component is initialized in this stage.

  2. Mounting: In this stage, a component appears on the screen which is called component mount.

  3. Update: A stage where the state of the variable changes.

  4. Unmount: A component is not visible on the page it is unmounted. It happens when the user moves to a different screen and in many other cases.

Whenever there is a need to perform tasks during this component cycle one can use the react hook 'useEffect'.

Say for example a Card is one of the components which displays details of a user on the web page. We can perform actions with 'useEffect()' in the following cases:

  • If I want to fetch user details when the component is mounted.

  • If I want to send the changes to the database when edits are performed.

  • If I want to clear the data where ever user moves to another screen that means when a component is unmounted.

useEffect() :

Syntax

The syntax looks like useEffect(setup, dependencies) useEffect takes the following as parameters:

a. Here, setup is a call-back function

b. dependencies is an array that stores variables whose state change can be tracked. It is an optional value it can be empty.

Implementation:

Creating a useEffect hook. Consider a component file Counter and create a hook for that component.

  1. Performing an action when the component is mounted:
     import React,{useState, useEffect} from "react";
     import './index.css';
    
     export const Counter:React.FC = ()=>{
    
         useEffect(()=>{
             console.log("Component mounted");
         },[])
    
         const [counter,setcount] = useState<number>(0);
         const incrementCounter= ()=>{
             setcount(counter+1)
         }
         const decrementCounter= ()=>{
             if(counter>0)
             setcount(counter-1)
         }
    
         return(
             <div className="counter-container">
                 <h3>Counter</h3>
                 <div>
                     <h1>{counter}</h1>
                 </div>
                 <div>
                     <button className="b1" onClick={incrementCounter}>Incr</button>
                     <button className="b2" onClick ={decrementCounter}>Decr</button>
                 </div>
             </div>
         );
     }
    

    useEffect callback function is called and the console.log value is printed as soon as the component is mounted based on the number of times the component is used. To fetch the data when the component is mounted the fetch call can be written within the callback function.

  2. Performing actions when a state of a variable is changed. This is the update stage of the component lifecycle:

     import React,{useState, useEffect} from "react";
     import './index.css';
    
     export const Counter:React.FC = ()=>{
    
         const [counter,setcount] = useState<number>(0);
    
         useEffect(()=>{
             console.log("Component mounted");
         },[]);
    
         useEffect(()=>{
             console.log("Counter value updated");
         },[counter]);
    
         const incrementCounter= ()=>{
             setcount(counter+1)
         }
         const decrementCounter= ()=>{
             if(counter>0)
             setcount(counter-1)
         }
    
         return(
             <div className="counter-container">
                 <h3>Counter</h3>
                 <div>
                     <h1>{counter}</h1>
                 </div>
                 <div>
                     <button className="b1" onClick={incrementCounter}>Incr</button>
                     <button className="b2" onClick ={decrementCounter}>Decr</button>
                 </div>
             </div>
         );
     }
    

    The second useEffect hook prints a statement and its callback function is called as many times as the value of the counter is updated. So the functionality to be performed when the state change is encountered can be written in the callback function of useEffect hook where the variable whose state change is to be monitored is in its dependencies array. Here in the above example whenever the counter is updated the useEffect callback function is called.

  3. Performing actions when a component is unmounted:

    For this implementation, we need to add conditional rendering of a component based on the state of a variable.

    Code of file app.jsx where a component 'Counter' is being conditionally rendered.

     import React,{useState} from 'react';
     import {Counter} from './components/counter';
    
     export const App: React.FC = ()=>{
         const [state,setState] = useState<boolean>(true);
         return ( 
             <div>
                 <button onClick={(e)=>setState(!state)}>Shift State</button>
                 {state?<Counter/>:''}
             </div>
         )};
    

    Here using the Boolean state variable we are mounting and unmounting the component by changing the state value on the button click.

    Let us now look at the file where the component is described:

     import React,{useState, useEffect} from "react";
     import './index.css';
    
     export const Counter:React.FC = ()=>{
    
         const [counter,setcount] = useState<number>(0);
    
         useEffect(()=>{
             console.log("Component mounted");
             return function(){
                 console.log("component unmounted")
         };
         },[])
    
         useEffect(()=>{
             console.log("component updated");
         },[counter])
    
         const incrementCounter= ()=>{
             setcount(counter+1)
         }
         const decrementCounter= ()=>{
             if(counter>0)
             setcount(counter-1)
         }
         return(
             <div className="counter-container">
                 <h3>Counter</h3>
                 <div>
                     <h1>{counter}</h1>
                 </div>
                 <div>
                     <button className="b1" onClick={incrementCounter}>Incr</button>
                     <button className="b2" onClick ={decrementCounter}>Decr</button>
                 </div>
             </div>
         );
     }
    

    Here, in the first useEffect hook it returns a function this function is called when ever the component is unmounted. using the button when we change state the component is unmounted and the return function is called. So, to implement a login when component is unmounted it can be described in a function returned by a useEffect hook. On every unmount the function is called.