Say I have React component where I render a table data with the following. I also have a table column called Total which is a calculated field. I know that it can be calculated within the rendered function ex: price*qty. This can also be beautified by adding this to a function. But for every row, this function will be called. Looks expensive to me. My question is, is this the right way in React when it comes to performance?
Alternatively, I can call the map function where I calculate the fields beforehand and trigger the render. The problem I see in this approach is that it looks redundant. Every time qty or price value changes I have to calculate manually.
PS: I have the data in structure in an Interface.
In reality, I have a large dataset to render, and calculation can get lil complex. What is the best way to approach this?
[{"name": "Plumbing", "price": 50, "qty": 3},
{"name": "Fixing", "price": 150, "qty": 1},
{"name": "Welding", "price": 145, "qty": 9}]
If each row's quantity changes independently of other rows, I would create a component to represent the row, and have the component own the logic for updating its quantity, and therefore its Total
This would guarantee that only the row whose quantity changed re-renders, instead of the whole table
const Table = () => {
const rows = [
{
name: 'Plumbing',
price: 50,
qty: 3,
},
{
name: 'Fixing',
price: 150,
qty: 1,
},
]
return (<div>
{rows.map(r => <TableRow key={r.name} name={r.name} qty={r.qty} price={r.price} />}
</div>
);
}
const TableRow = ({name, qty, price}) => {
const [quantity, setQuantity] = React.useState(qty)
const handleQtyChanged = (event) => setQuantity(event.target.value)
return (<p>
<span>{name}</span>
<input value={quantity} onChange={(e)=> handleQtyChanged(e)} />
<span>{quantity * price}</span>
</p>)
}