Write a React Component Like a Pro
In the world of React, writing components is an art. It’s not just about making them work — it’s about making them work well. Today, we’re going to look at how to craft your components like a pro, focusing on readability, reusability, and efficiency.
// src/components/List.js
import React from 'react';
const List = ({ data }) => {
return (
<ul>
{data.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
};
export default List;
This component takes an array of data and renders it as a list.
Enhancing Components with HOCs
Higher-Order Components (HOCs) are a powerful pattern for reusing component logic. They essentially wrap a component to extend its functionality without altering its structure.
For example, a withLoading HOC can be used to display a loading state:
// src/hocs/withLoading.js
import React, { useState } from 'react';
function withLoading(Component) {
return function WithLoading({ isLoading, ...props }) {
if (isLoading) {
return <div>Loading...</div>;
}
return <Component {...props} />;
};
}
export default withLoading;
Comments