#2 React Hooks useEffect()

#2 React Hooks useEffect()

Intro to useEffect() hook

Initially when page get loaded useEffect() is the first function to render automatically and it runs every time when ever they are changes or updates done to content in the website data. Without rendering data every time it will only render when ever some new changes done by depending on parameter. Lets see in the below example.

Sample code using UseEffect()

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

const useEFfect = () =>{
    const [routePath, setRoutePath] = useState('users');
    const [items, setItems ] = useState([]);
    useEffect(() =>{
        fetch(`https://jsonplaceholder.typicode.com/${routePath}`)
        .then(response => response.json())
        .then(json => setItems(json))
        console.log('rendering');

        return() =>{
            console.log('pre-rendering');
        };
    },[routePath])

    return(
        <Fragment>

            <button onClick={()=> setRoutePath('users')}> Users </button>
            <button onClick={()=> setRoutePath('posts')}> Posts </button>
            <button onClick={()=> setRoutePath('comments')}> Comments </button>
            <h1>{routePath}</h1>
            { items.map( item =>{
                return <pre> {JSON.stringify(item)}</pre>
            })}

        </Fragment>
    );


};

export default useEFfect;

Here when the page loaded it useEffect() will first fetch data from dummy data from that URL and then it renders into jsx

Explaining Syntax & Clean up

useEffect( () =>  { 
               some function which renders data 
               return() =>{
            console.log('pre-rendering');
        };
}, 
             [ dependent variable, varible 2  ] )

In above syntax useEffect will render data only when that dependent variable data is changed. Otherwise it will only rendered once. We can give more than one dependent variables.

If there are many records while fetching the data, useEffect() will increase rendering cycle as per data, If we use return statement after your fetch() logic, data will be only rendered on the web page after it acquires complete data from API it's called Clean Up. You can play with my code by running locally or in sandbox Github link observe console by removing return() and with return() statement.

Throw Back

Before React 16.8 developers need to use 3 functions to this same task they are

componentDidMount()
componentDidUpdate()
componentWillUnmount()

Here there is redundancy with same logic every time for componentDidMount() and componentWillUnmount() so to avoid all these React developers came up with useEffect() which will cover these 3 functions.

Conclusion

UseEffect() is doing a great job and made web developers job simple by overcoming these redundant functions which will do the same job.

Thank You for reading till now... Lets learn about other hooks in next blog,