useEffect Hook

Sanjana Human In Tech
2 min readMay 23, 2024

--

The useEffect hook in React is used to perform side effects in function components. These side effects may include data fetching, subscriptions, or manually changing the DOM in React components.

The useEffect hook takes two parameters:

  • A function: This function will be called after the component renders. It can perform any side effects.
  • An optional array of dependencies: This array specifies values (usually props or state) that the effect depends on. If any of these values change, the effect will re-run. If the array is empty, the effect will only run once after the initial render, similar to componentDidMount in class components.

In the example code you provided:

useEffect(() => {
fetchData();
}, []);

The useEffect hook runs once after the component mounts because the dependency array [] is empty. This means there are no dependencies, so the effect doesn't depend on any prop or state changes. Therefore, it only runs once after the initial render, similar to componentDidMount in class components.

In this specific case, it’s being used to trigger the fetchData function when the component mounts. So, fetchData will be called once when the component is first rendered to fetch data from the API. The useEffect hook runs once after the component mounts because the dependency array [] is empty. This means there are no dependencies, so the effect doesn't depend on any prop or state changes. Therefore, it only runs once after the initial render, similar to componentDidMount in class components.

In this specific case, it’s being used to trigger the fetchData function when the component mounts. So, fetchData will be called once when the component is first rendered to fetch data from the API.

--

--

Sanjana Human In Tech
Sanjana Human In Tech

Written by Sanjana Human In Tech

A React Native front-end enthusiast and dedicated development engineer, eager to expand knowledge on development techniques and collaborate with others.

No responses yet