DEV Community

loading...
Cover image for useEffect with and without dependency array in react

useEffect with and without dependency array in react

Aastha Pandey
I write only on those topics, wherein I myself was stuck at some point in time.
・1 min read

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.

Discussion (3)

Collapse
aasthapandey profile image
Aastha Pandey Author

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.