DEV Community

Cover image for What is useEffect Hook in ReactJS?How useEffect works and where to use it?
Abdul Waqar
Abdul Waqar

Posted on • Updated on

What is useEffect Hook in ReactJS?How useEffect works and where to use it?

Prerequisite: Knowledge of JavaScript and Basic knowledge of ReactJS.

This post covers about useEffect hook of ReactJS. What is the uses of

useEffect? What is syntax ? How does it work? When to use it ? And Some common use cases of useEffect Hook.

What is React?

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called “components”.

What is useEffect() ?

Our React Application interact with outside world with functions. useEffect is ReactJS Hook which is used to handle side effect functions(side effect function are those function that communicate with outside world or just out of ReactJS ecosystem ) and by using useEffect we can separate them into other function.
useEffect hook must be declared inside the React component at top level of function. it gives several advantages :
*It will have access to those data that is required in useEffect hook.

  • It cal also update the data later base on the dependency and updates. ## What is Syntax of useEffect hook? It accepts a function that interact with outside world of React components and array of dependency. If we want to execute useEffect after a specific event or state change we will pass our variables in array of dependency . Every time a variable passed to useEffect dependency arrayk is updated useEffect hook will be re-called.
useEffect(function sideeffect(){
.....
}, [array_of_dependency ])
Enter fullscreen mode Exit fullscreen mode

About hook

  • if we don’t pass dependency variable then useEffect hook will only called when our component is rendered .
  • If we pass an empty array to useEffect then our component will be rendered for first time when a component is rendered. To re-call useEffect hook we have to refresh our page.
  • If we pass dependencies to useEffect hook, then useEffect will executed every time when the variables which we passed to dependency array .

How does it work?

Every time a React components finish rendering, useEffect run unless you specified dependencies in the dependencies array.

When to use useEffect()?

There are several cases where we should consider using useEffect hook. Most import of them are :

  • If we want to hit an API endpoint to fetch data and display data on client side. When our component is rendering, function or handler passed to useEffect hook called and data fetched in component states. Then these states are used in UI components.
  • When we want to fetch data based on passed parameter, we can updated this parameter from client side. Once the parameter is updated to new data , useEffect hook will be re-called.
  • We should useEffect, when your component depends on the outside world data, and we can not guarantee that data will come or not (maybe the server is down there). So, Instead of throwing errors and stop other components from being rendered, move them into useEffect hook.
  • When you are using browser API including Timer function, fetch API, local storage and for more browser API, please refer : MDN Browser API.

Some use cases of React useEffect hook

  1. Always run whenever component renders/re-renders
import React, { useEffect } from "react";
const UseEffectHookExmaple = () => {
  useEffect(() => {
    document.title = "UseEffect called when a component Rendered";
  });
  return (
    <div>
      <h1>UseEffect Hook Called every time a component is rendered</h1>
    </div>
  );
};

export default UseEffectHookExmaple;
Enter fullscreen mode Exit fullscreen mode

2.Run once after that if component re-renders, then it will not run.

import React, { useEffect } from "react";
const UseEffectCalledOnce = () => {
  useEffect(() => {
    document.title = "UseEffect called Once when component Rendered";
  }, []);
  return (
    <div>
      <h1>UseEffect called Once when component Rendered</h1>
    </div>
  );
};

export default UseEffectCalledOnce;
Enter fullscreen mode Exit fullscreen mode

3.Run once by default after that if prop values changes, then run

import React, { useEffect } from "react";
const UseEffectCalledOnce = ({ PageTitle }) => {
  useEffect(() => {
    document.title = PageTitle;
  }, [PageTitle]);
  return (
    <div>
      <h1>UseEffect called when PageTitle is updated</h1>
    </div>
  );
};

export default UseEffectCalledOnce;
Enter fullscreen mode Exit fullscreen mode

If you have any suggestion please let us know in comment section.
GITHUB
Twitter

Top comments (7)

Collapse
 
marzelin profile image
Marc Ziel • Edited

What about a cleanup function?

If I want some code to run on every render, should I put it in a useEffect or directly in a component and what's the difference between those approaches?

What are common pitfalls when using useEffect?

What are differences between mounting, rendering and updating the DOM? When is useEffect really called?

Collapse
 
devparkk profile image
Dev Prakash

It is not guaranteed that useEffect function will be called on every rerender .
But in the following case it will :
If you pass some state in the dependency array , so whenever that state changes its value then it would mean two things to the react . changing this value will cause useEffect function to be called again , and also since this is a state , it will rerender the component .
Order of execution will be( after initial render ) :
1 . New component will be rendered and it will be displayed on to the browser (also called painted on to the browser )

2 . if you have defined some cleanup function , then cleanup function will be called for the previous component .
3 . At last useEffect function will be called for this new component .

There is this beautiful and comprehensive article on the same by Dan Abramov . overreacted.io/a-complete-guide-to...
Take a look for better understanding .

Happy coding

Collapse
 
mikenatsu profile image
MikeNatsu • Edited

for a cleanup function you would use return inside of it, might look like this

useEffect(()=>{
// Code
return () => {
//code
}

},[]);

here's an example from react docs

reactjs.org/docs/hooks-effect.html...

Collapse
 
chetan_atrawalkar profile image
Chetan Atrawalkar

Can I used multiple useEffect in one function.

Collapse
 
frankytse_07 profile image
Franky Tse • Edited

In short yes. Personally I follow the "Single Responsibility Principle" when it comes to useEffect

Collapse
 
abdulwaqar844 profile image
Abdul Waqar

You can create multiply sub components then import them in parent component. In subcomponent, you can use useEffect hook as well as in the parent component.

Collapse
 
abdulwaqar844 profile image
Abdul Waqar

🤔