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 Kevin Marville Insights

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 *

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Find out more about Webmentions.)