Dealing with Side Effects with the useEffect() Hook
In order to deal with side effects such as the HTTP request shown previously in a safe way (that is, without creating an infinite loop), React offers another core Hook: the useEffect()
Hook.
The first example can be fixed and rewritten like this:
import { useState, useEffect } from 'react';
import classes from './BlogPosts.module.css';
async function fetchPosts() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const blogPosts = await response.json();
return blogPosts;
}
function BlogPosts() {
const [loadedPosts, setLoadedPosts] = useState([]);
useEffect(function () {
fetchPosts().then((fetchedPosts) => setLoadedPosts(fetchedPosts));
}, []);
return (
<ul className={classes.posts}>
{loadedPosts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
export default BlogPosts;
In this example...