Don't use isLoading booleans as source of truth.
Why? to avoid impossible states. If an error happens when fetching users, we would have an impossible state for a fraction of ms:
const App = () => {
const [isLoading, setIsLoading] = React.useState(false);
const [error, setError] = React.useState("");
const fetchUsers = async () => {
try {
setIsLoading(true);
fetch(/*... */);
} catch (error) {
setError("Upps, an error occurred");
} finally {
setIsLoading(false);
}
};
React.useEffect(() => {
fetchUsers();
}, []);
if (isLoading) {
return <p>Is Loading ... </p>;
}
if (error) {
return <p>{error} </p>;
}
return <p>Great we have some users data</p>;
};
Use boolean variables that are derived from a source of truth:
Our source of truth is status
. We can create boolean variables derived from that like so:
const App = () => {
const [status, setStatus] = React.useState("idle");
const fetchUsers = async () => {
try {
setStatus("pending");
fetch(/*...*/);
setStatus("successful");
} catch (error) {
setStatus("rejected");
}
};
React.useEffect(() => {
fetchUsers();
}, []);
if (status === "pending" || status === "idle") {
return <p>Is Loading... </p>;
}
if ((status = "rejected")) {
return <p>Upps, an error occurred </p>;
}
return <p>Great we have some users data</p>;
};