React Hook #2 useEffect()

Subscribe to my newsletter and never miss my upcoming articles

React Hooks are v16.8 specification which allows certain backward compactible functionalities without any use of class based ordering.

Here lets see the useEffect hook, cleanup function, second parameter and finally the use case implementation fetch data.

Effects in React Component

Effects are more of a self explanatory concept provided by react hooks.

Effect in context is any action to be performed after a the final render or after the specified changes in the DOM, as for this purpose we come across useEffect()

Evoke after the re-render

The re-render implies that after the initial render of components if there tends to be any DOM update useEffect() comes into picture and performs its own actions.

Hook based chunk

Previously v16.7 of react there exist the class based chunk, which includes the constructor, this keyword, binding and stuff which are probably messy compared to the function based chunk provided as useEffect()

Implementation

Interactive example to see the window width using useEffect.

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

const exploreUseEffect = () => {
   const [size,setSize]=useState(window.innerWidth);

   const checkSize = () => {
      setSize(window.innerWidth);
   };

   useEffect(() => {
      window.addEventListener('resize', checkSize);
   });

   return <>
      <h1>Window Size</h1>
      <h2>{size} PX</h2>
   </>
}

Cleanup Function

The function that calls exactly after the useEffect() function is the cleanup function.

Cleanup function is one of the best practice for useEffect()

Let's see it for the above example.

   useEffect(() => {
      window.addEventListener('resize', checkSize);
      return () => {
         window.removeEventListener('resize', checkSize);
      }
   });

Second Parameter

This is completely relied for the performance issue, as so far from the explanations useEffect functions run after every re-render, we can skip a run by passing in the second parameter, as array of state values to look for, so useEffect runs only when one of the state value changes.

Lets look how it works for the following example.

   useEffect(() => {
      window.addEventListener('resize', checkSize);
      return () => {
         window.removeEventListener('resize', checkSize);
      }
   }, []);             /*so an empty array is passed as second parameter*/

As for the above code, useEffect runs only once.

Use Case

Let's move on to the best part as we implement fetching and displaying the data. As we see to it initially the background with some kind of heading comes in then/after which the data gets display, so we see a scope for useEffect to shine in here.

Implementing github user profiles by fetching github API.

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

const url = 'https://api.github.com/users';

const UseEffectFetchData = () => {

  const [users, setUsers] = useState([]);

  const getUsers = async () => {
    const response = await fetch(url);
    const users = await response.json();
    setUsers(users);
  }

  useEffect(() => {                  /*after the initiall render*/
    getUsers();                        
  })
  return <>
    <h3>GitHub Users</h3>
    <ul className="users">
      {users.map((user) => {     /*extract data to display the list*/
        const { id, login, avatar_url, html_url } = user;
        return <li key={id}>
          <img src={avatar_url} alt={login} />
          <div>
            <h4>{login}</h4>
            <a href={html_url}>profile</a>
          </div>
        </li>
      })}
    </ul>
  </>;
};

export default UseEffectFetchData;

Major Takeaway

A useEffect is a hook, a hook is a function provided by React that let us hook to react features from function component

After any change/DOM updation there is an effect so called the useEffect.


Hope you all liked the post, share your impressions and queries below <3

Let's connect

Social links

No Comments Yet