The useEffect() Hook is used to run "side-effects" in your component. Another way to think about side effect code is that functional components have only one job: return JSX content to render. If the component needs to do something else, such as fetching API data, this should be done in a useEffect() Hook. For example, if you were to just make the API call as part of your component function, you would likely introduce race conditions and other difficult-to-fix buggy behavior.
Let's take a look at an example that fetches API data using Hooks:
import React, { Fragment, useEffect, useState } from 'react';
function fetchUser() {
return new Promise(resolve => {
setTimeout(() => {
resolve({ id: 1, name: 'Adam' });
}, 1000);
});
}
export default function App() {
const [id, setId] = useState('loading...');
const [name, setName] = useState('loading...');
useEffect(() => {
fetchUser().then(user...