What is side effect in React?

Experience Level: Junior
Tags: React

Answer

In React, a side effect is any change to the state or behavior of the application that is not directly related to rendering the user interface. Side effects can include things like fetching data from an API, updating the browser's location, or setting a timer. In general, side effects are things that happen outside of the normal flow of the application and can have an impact on other parts of the system.

In React, side effects are typically managed using the useEffect hook. This hook allows you to perform side effects in a declarative way, by specifying what should happen when a component mounts, updates, or unmounts. For example, if you need to fetch data from an API when a component mounts, you can use the useEffect hook to do so:

import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <div>
      {data ? (
        <p>Data: {data}</p>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

In this example, we use the useEffect hook to fetch data from an API when the component mounts. We pass an empty array as the second argument to useEffect, which tells React to only run the effect once (when the component mounts). We then update the component's state with the fetched data, which causes the component to re-render with the new data.

React for beginners
React for beginners

Are you learning React ? Try our test we designed to help you progress faster.

Test yourself