DEV Community

Sidra Maqbool
Sidra Maqbool

Posted on

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.

Top comments (0)