I don’t know if I’m following an advisable/correct pattern but basically, my application leverages on same arrays used in various components.
I am thinking about generalizing these lists as constants for simplicity/maintainability.
Here follows an example: I have two different arrays with fixed labels but dynamic contents. The first array retrieves the content info using the "props" I am passing to the contents while the second one uses new data fetched with useEffects.
Note that I render these arrays in many different ways so it may be better to not fix the rendering.
import {useState, useEffect} from "react";
export default function App({ props }: Props) {
const [dataIntegration, setDataIntegration] = useState(null);
useEffect(() => {
const fetchDataIntegration = async () => {
const { data, error } = await client
.from("someTable").select("*").eq("id", props.id);
if (error) {
console.error(error);
return;
}
if (data) {
setDataIntegration(data[0]);
}
};
fetchDataIntegration();
}, []);
const items1 = [
{ fixedLabel: "Fixed Label 1", variableContent: props?.content1 },
{ fixedLabel: "Fixed Label 2", variableContent: props?.content2 },
];
const items2 = [
{ fixedLabel: "Fixed Label 1", variableContent: dataIntegration?.content1 },
{ fixedLabel: "Fixed Label 2", variableContent: dataIntegration?.content2 },
];
return (
<div>
<div>
{items1.map((item1) => (
<div key={item2.fixedLabel}>
<div>
{item1.variableContent}
</div>
</div>
))}
</div>
<div>
{items2.map((item2) => (
<div key={item2.fixedLabel}>
<div>
{item2.variableContent}
</div>
</div>
))}
</div>
</div>
);
}
2
Answers
As per my experience, when working on big codebases it’s generally a good idea to put these arrays or any constant data in a constant file for ease of maintainability.
You are correct in wanting to generalize these. Whenever you have code that is very repetitive – as the items1, items2, etc suggests – you should try to simplify.
So instead of doing:
It would be better maintainable and reusable like this:
From there, you can fill up array with items or call them manually.