What's the Problem?
Before exploring a solution, it's important to first understand the concrete problem.
Actions that are not directly related to producing a (new) user interface state often clash with React's component rendering cycle. They may introduce bugs or even break the entire web app.
Consider the following example code snippet:
import { useState } 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([]);
fetchPosts().then((fetchedPosts) => setLoadedPosts(fetchedPosts));
return (
<ul className={classes.posts}>
{loadedPosts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
export default BlogPosts;
Don...