DEV Community

Cover image for useEffect with and without dependency array in react
Aastha Pandey
Aastha Pandey

Posted on

useEffect with and without dependency array in react

When I was just starting with react, the issue I faced was, useEffect hook of react got called every time state or props got changed.


import React, { useState } from "react";
export default function App() {
  const [count, setCount] = useState(0);
  const [data, setData] = useState(0);
  React.useEffect(() => {
    console.log("useEffect called!");
  });
  return (
    <div className="App">
      <label>count </label>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        {count}
      </button>
      <hr />
      <label>data </label>
      <button
        onClick={() => {
          setData(data + 1);
        }}
      >
        {data}
      </button>
    </div>
  );
}

})
Enter fullscreen mode Exit fullscreen mode

In the above snippet, there is no dependency array so this will be called every time if state or props changes.
To resolve this we can use dependency array.

//rest of the code is same 
 React.useEffect(() => {
    console.log("useEffect called!");
  },[data]); //adding dependency array
Enter fullscreen mode Exit fullscreen mode

In the above snippet, there is a dependency array so this will only be called first when the component is being mounted and second if the dependency in that array, which is data, changes.
And also, there could be more than one dependency.

Top comments (3)

Collapse
 
aasthapandey profile image
Aastha Pandey

Hey! thebarefootdev, even I know that the code won't do anything I was not trying to tell about Api calls or fetch or axios or async await or promise or then, I was only trying to point about the dependency array.

Collapse
 
vupadhayayx86 profile image
vupadhayayx86

I think instead of saying "In the above snippet, there is no dependency array so this will be called every time if state or props changes." we can say the useEffect function is called at the beginning of the load page instead of calling it every time. As the useEffect does not have dependencies the useEffect get triggered when the page load.

Collapse
 
nikulsagadhara profile image
Nikul Sagadhara

If we don't put a dependency array, useEffect() will be called on every render.