WithLoading HOC

WithLoading HOC

Loading behavior to any component.

const withLoading = (Component) => {
return function WithLoadingComponent({ isLoading, …props }) {
if (isLoading) return <p>Loading…</p>;
return <Component {…props} />;
};
};

Let’s apply it to our ReusableList:

const EnhancedList = withLoading(ReusableList);

const App = () => {
const [isLoading, setIsLoading] = React.useState(true);
const [users, setUsers] = React.useState([]);

React.useEffect(() => {
setTimeout(() => {
setUsers([
{ id: 1, name: ‘John Doe’, age: 30 },
{ id: 2, name: ‘Jane Smith’, age: 25 },
]);
setIsLoading(false);
}, 2000);
}, []);

return (
<div>
<h1>User List</h1>
<EnhancedList
isLoading={isLoading}
items={users}
renderItem={(user) => (
<div>
<h2>{user.name}</h2>
<p>Age: {user.age}</p>
</div>
)}
/>
</div>
);
};

In this example, the withLoading HOC wraps around ReusableList, adding loading state management to it. This pattern promotes code reuse by enhancing components with additional logic without modifying the original component.


Discover more from Kvnbbg.fr

Subscribe to get the latest posts sent to your email.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *