DEV Community

Nissrine Canina
Nissrine Canina

Posted on

1

useEffect Hook

Definition

The useEffect hook is used to handle the side effect of React functional components outside of returning JSX. For instance, fetch data from an API when a component loads. Another example consists of starting or stopping a timer. Also, the useEffect allows to make manual changes to the DOM.

Any code defined inside the useEffect hook will run after React components finished the DOM updates. By default, useEffect runs both after the first render as well as whenever the component's state updates.

useEffect Dependencies Array

The default behavior of useEffect does not always agree with the purpose of our code. To adjust this behavior, we can run useEffect hook functions conditionally using dependencies array.

  • Empty array of dependencies[]:

for Example, we only need to run a fetch call to an API once after the JSX has completely loaded. Adding an empty dependencies array as a second argument to the useEffect function will stop the fetch call to API from happening with every re-render of the components. Therefore, the fetch call will only occur when the component renders for the first time.

  • Dependencies array with one or more elements [element1, element2,..]:

Using the example of an incrementing counter running as a side effect. We can add the counter variable to the dependencies array. Therefore, the useEffect will run every time our counter state changes.

Conclusion

  • Using useEffect with no dependencies array means that the side effect will run every time the component renders and whenever state or props change.
  • Using useEffect with an empty dependencies array means the side effect will only run the first time the component renders. No state is involved in this case.
  • Using useEffect with dependencies with elements in it means that the side effect will run every time those elements/variables change. The side effect will be triggered by the state changes of the elements inside the dependencies array.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay