I’m developing a React App which fetches data from DB every 5 seconds and displays it. The data is an array of objects, each with three properties:
- Name
- Status (Run/Hold)
- Update Time
The data is displayed in a component called DisplayStations
, which also contains a toolbar on the top that counts the number of active stations.
Currently, when the state of DisplayStations
is updated with a new array, all the stations are re-rendered, but I want only the changed stations to be re-rendered. What is the best approach for solving this issue?
- Code:
function DisplayStations() {
const [stationsData, setStationsData] = useState([]);
.
.
.
useEffect(() => {
const fetchStationsData = async () => {
const response = await fetch(`/stationsInfo`);
const data = await response.json();
setStationsData(data);
handleStationsDataChange();
};
fetchStationsData();
const fetchInterval = setInterval(() => {
fetchStationsData();
}, intervalTime * 1000);
return () => {
clearInterval(fetchInterval);
};
});
.
.
.
return (
<Box>
{stationsData.map((stationsDataObj) => {
return <Station key={stationsDataObj['Name']} stationData={stationsDataObj} />;
})}
</Box>
);
}
function Station({ stationData }) {
return (
<div>
<div>
{stationData['Name']}
</div>
<div>
{stationData['Status']}
</div>
<div>
{stationData['updateTime']}
</div>
</div>
}
I’m developing a React App which fetches data from DB every 5 seconds and displays it in the DisplayStations
component. The data is an array of objects, each with three properties: Name, Status (Run/Hold) and Update Time. The component also contains a toolbar that counts the number of active stations.
Currently, when the state of DisplayStations
is updated with a new array, all the stations are re-rendered, but I want only the changed stations to be re-rendered. What is the best approach for solving this issue?