DEV Community

Sidra Maqbool
Sidra Maqbool

Posted on

1

How to Handle Side Effects like API Calls in React Components

When developing React applications, handling side effects such as API calls is crucial. The primary tool for this in the React ecosystem is the useEffect hook. Here's a simple guide to help you manage those side effects:

Understanding useEffect:
The useEffect hook allows you to perform side effects in function components. It takes two arguments: a function where you place your side effect and a dependency array. The side effect will re-run whenever any value in the dependency array changes.

Making an API Call:

const [data, setData] = useState(null);

useEffect(() => {
  fetch('/api/data')
    .then(response => response.json())
    .then(data => setData(data))
    .catch(error => console.error("There was an error fetching data:", error));
}, []);

Enter fullscreen mode Exit fullscreen mode

In the example above, we're making an API call using the fetchfunction. The empty dependency array [] ensures the effect only runs once, similar to componentDidMountin class components.

Handling Loading & Errors:
To provide better UX, it's a good idea to handle loading states and errors.

const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
  fetch('/api/data')
    .then(response => response.json())
    .then(data => {
      setData(data);
      setLoading(false);
    })
    .catch(error => {
      console.error("There was an error fetching data:", error);
      setError(error);
      setLoading(false);
    });
}, []);

Enter fullscreen mode Exit fullscreen mode

Cleaning Up Side Effects:
Sometimes, you might set up subscriptions or listeners that need cleanup. To do this, return a cleanup function from your effect:

useEffect(() => {
  const subscription = someAPI.subscribe(data => {
    setData(data);
  });

  return () => {
    subscription.unsubscribe();
  };
}, []);

Enter fullscreen mode Exit fullscreen mode

Using Libraries:
For more complex scenarios or to streamline your API calls, consider libraries like axiosfor HTTP requests or react-query and SWRfor data fetching, caching, and synchronization.

Conclusion:
Handling side effects, especially API calls, in React is straightforward with the useEffecthook. Ensure you manage loading states, errors, and potential cleanups to provide an optimal experience for your users.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay