DEV Community

Cover image for useEffect: Understanding The Sidekick For Handling Side Effects In React
bosofisan
bosofisan

Posted on

useEffect: Understanding The Sidekick For Handling Side Effects In React

In the world of React, side effects play an important role in interacting with the outside world, fetching data, updating the DOM, and managing subscriptions. useEffect is the perfect tool to orchestrate the side effects within these components to ensure a harmonious overall experience.

What Is useEffect?
useEffect is a hook in React that allows you to perform side effects in your components. You're essentially telling React that your component needs to do something else after it's rendered. The hook helps with things like fetching data and DOM manipulation.

useEffect In Action

Image description
This is essentially the general syntax for useEffect.

  • The effect function encapsulates the side effect function
  • The dependency function (optional) controls when the effect will re-run

The following is an example of useEffect with fetch:

Image description

Let's break things down

Image description

  • useState is being used to manage two states: data to store the fetched data and error to track any errors

Image description

  • The fetchData function handles fetching the data by using fetch to make the API call, parsing the response as JSON, and updating the data state if successful or the error state if it fails.

Image description

  • The useEffect hook executes the fetchData function when the component mounts ([]: dependency array).

Conclusion
Overall, useEffect has emerged as the React developer's secret weapon. This powerful hook empowers us to seamlessly integrate external interactions, data fetching, and DOM manipulation, all within the graceful rhythm of our functional components. By mastering its nuances, we unlock a world of possibilities for building dynamic, responsive, and engaging user experiences.

Top comments (0)