Skip to main content

Command Palette

Search for a command to run...

A Brief Summary of the useEffect Hook

An Overview

Published
3 min read

Hooks play a vital role in the modification of functional components and reduces the ambiguity with respect to carrying out certain tasks in react. One of those such hooks introduced in React 16.8 is the useEffect() Hook.

The useEffect hooks is a hook used primarily for setting up side effects in a component , it means that the useEffect is use to trigger or cause a side reaction when a specific change occurs in the component i.e after rendering a function, the useEffect re-renders the function based on the specified changes. This change includes changing a state value, adding a state value, setting up event listeners, fetching API etc. We make use of the useEffect alongside the useState hook which preserves the value between the initial rendering and re-rendering. useEffect Syntax*

useEffect(() => {
  console.log('This is a side effect')
})

This is the default syntax for a useEffect hook but however this side effect will now run on every single render of the component. That means when the component mounts ,when the props change, and/or when the state changes. This is really nice, however it is not ideal if a side effect is only desired on at every instance the component renders and/or when certain props or state change.

This necessitated to an optional second parameter generally called the dependency array.A dependency array is an array that is passed into the useEffect as a second argument, which primarily ensures that after the first render, the function would not re-render at the instance when a prop or a state is changed. We can also pass in values into the array which will in turn render when the value is updated or changed.

Code:

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

const useEffectBasics = () =>{
const [name, setName] = useState("Grace")

// Second Parameter  runs at first render
  useEffect(() => {
    console.log("Hello world")
  }, []);


//In this case below the useEffect runs when we update the value of the name only
 useEffect(() => {
    console.log(name)
  }, [name]);


  return <>
  <h1>{name}</h1>
  <button  onClick={()=> setName("Michael")}>Click me</button>
  </>;
}

Clean Up Function The last scenario is the clean up function in the case of using event listeners, at each instance of dynamically running the function which in turn gives many event listeners, which if they are not cleaned up they will affect our app. It removes, updates and adds the new state or value.

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

// cleanup function

const Cleanup = () => {
  const [size, setSize] = useState(window.innerWidth);
  // console.log(size)

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

  useEffect(() => {
    console.log('SideEffect')
    window.addEventListener('resize', checkSize);
    return ()=>{
      console.log('cleanup')
      window.removeEventListener('resize', checkSize)
    }
  }, []);

  console.log('render')
  return (
    <>
    <h1>window</h1>
    <h2>{size}</h2>
    </>
  );
};