Search code examples
reactjsuse-effect

React get request with useEffect and without it


What is the difference between these three codes?

1:

     axios.get('https://jsonplaceholder.typicode.com/posts')
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
  });
function App() {

  return (
    <div className="App">
      <p>Learn React</p>
    </div>
  );
}

export default App;

2:

function App() {
  useEffect(() => {
    axios
      .get('https://jsonplaceholder.typicode.com/posts')
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
      });
  }, []);

  return (
    <div className="App">
      <p>Learn React</p>
    </div>
  );
}

export default App;

3:

function App() {
  axios
    .get('https://jsonplaceholder.typicode.com/posts')
    .then((res) => {
      console.log(res);
    })
    .catch((err) => {
    });

  return (
    <div className="App">
      <p>Learn React</p>
    </div>
  );
}

export default App;

All there seems to work with a slight difference. Why do we use useEffect? it seems to work perfectly without using it. whats is the difference between that one in which I used useEffect and the others?


Solution

  • The first example performs the AJAX operation once, when the application loads, and then never again. Because it's not part of the component, it's just executed as soon as the JavaScript module is processed.

    The second example performs the AJAX operation any time an instance of the <App> component is loaded, but only on that initial load. The operation would be performed again if you were to load a new instance of the <App> component. (Which is unlikely for an idiomatic <App> component, but likely for most components.)

    The third example performs the AJAX operation literally every time the <App> component renders. If you were to set any state which triggers a re-render, you'll re-invoke the AJAX request. This is unlikely to be desired behavior.

    All there seems to work with a slight difference.

    In this minimal contrived example, yes. The application being shown here has no real complexity and only one component.

    Why do we use useEffect?

    To perform an operation on any given render of a component depending on the array of dependencies uses in the call to useEffect. The operation is performed only when items in the dependency array change. If an empty array is provided, the operation will only occur on the first render of that instance of the component.