ReactJS Design Pattern ~Guard Clause Rendering~
Source: Dev.to
Overview
This pattern uses early return statements at the beginning of a component’s render function to handle edge cases, loading states, or invalid data. By returning early for these conditions, the main JSX return statement stays clean and flat, improving readability and maintainability.
Example
import { useState } from "react";
function Loading() {
return
Loading...
;
}
function Error() {
return
Error!
;
}
function UserProfile({ loading, error, user }) {
if (loading) return ;
if (error) return ;
return (
## {user.name}
{user.email}
{user.role}
);
}
function App() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
const user = {
name: "John Doe",
email: "Sample@example.com",
role: "Software Developer",
};
return (
setLoading(!loading)}>Toggle Loading
setError(!error)}>Toggle Error
);
}
export default App;