I’ve been working on a React component to fetch data from the GitHub API using useEffect
. Here is my current implementation:
import { useEffect, useState } from "react";
const url = "https://api.github.com/users/emmeiwhite";
const MultipleReturnsFetchData = () => {
/** In this challenge, I want to get the github user from an API */
const [isLoading, setIsLoading] = useState(true);
const [person, setPerson] = useState(null);
const [error, setError] = useState(false);
const fetchUser = async () => {
try {
const response = await fetch(url);
// fetch gocha!
if (!response.ok) {
setError(true);
setIsLoading(false);
return;
// we simply return in this case and our error state is true which will output the if(error) condition in the browser!
}
const user = await response.json();
console.log(user);
setPerson(user);
setIsLoading(false);
} catch (e) {
setError(true);
setIsLoading(false);
console.log(error);
}
};
useEffect(() => {
fetchUser();
}, []);
/** Order matters here:
* First comes loading, then error and only then the normal JSX return from the component
*/
if (isLoading) {
return <h1>Loading ...</h1>;
}
if (error) {
return <h1>There was an error ...</h1>;
}
const styles = {
width: "150px",
borderRadius: "100%",
};
return (
<article>
<img
src={person.avatar_url}
alt={person.login}
style={styles}
/>
<h1>{person.name}</h1>
<h3>Works at {person.company}</h3>
<p>{person.bio}</p>
</article>
);
};
export default MultipleReturnsFetchData;
My instructor mentioned that we would not need useEffect() any longer (after almost spending 14 lectures on useEffect & its use cases) as it is replaced by React Query (which the instructor will teach after so many section). This got me curious about the future of useEffect in modern React development.
My Questions:
-
Is useEffect becoming obsolete for data fetching with the rise of
React Query? -
Are there scenarios where useEffect is still preferred or necessary
despite the capabilities of React Query? -
How do you decide between using useEffect and React Query in your
projects? -
Additionally, considering the learning curve associated with
useEffect, should new learners avoid it and start with React Query
instead?
I understand that useEffect is a general-purpose hook used for various side effects beyond data fetching, such as subscriptions, manual DOM manipulations, and more. However, I’m particularly interested in how its usage for data fetching is evolving with tools like React Query.
I appreciate any guidance on how to best leverage these tools in modern React development.