'Is it antipattern having array manipulations in React render like in the sample below? [closed]
I need to create new array of items from very complex props that includes array of objects. The component is class based component. I did all operations in render like below:
class Shop extends React.Component {
render() {
const clothesProducts = this.props.product.brands.filter(item => item.tag === 'clothes')
let filterednewProducts = []
let clothesProductsNames = []
... newProductNames.forEach((item, index) => {
if (newProductNames[index + 1] !== newProductNames[index]) {
filterednewProducts.push(item)
}
})
}
if (clothesProducts.length) {
clothesProductsNames = clothesProducts.map(item => item.clothes.name)
}
const totalProducts = [...filterednewProducts, ...clothesProductsNames] console.log(totalProducts)
return (
...
)
}
}
I want to ask if it's anti pattern having these kind of operations inside render method in the class based component?
Solution 1:[1]
I would not call it immediately an anti-pattern, but that is definitely not a clean solution.
Whether it is completely unacceptable depends on amount of data that you are manipulating and the frequency of re-renders of your component. You can verify that by estimating / reasoning about data (like I will have only a couple of elements in those arrays, operations are simple it will be fast) and by estimating the amount of renders (like This components rarely renders, so it does not matter that much).
You can examine operations performance deeper by using some predefined example data sets and measuring time of running that code. You can measure amount of re-renders e.g. by using React DevTools browser extension.
Or you can assume that it is not performant or may become not performant in the future - you cannot guarantee that data will not change or other developer will not make that component re-render more often. Just wrap it in useMemo
hook (for function components) or use other form of memoization to keep your hands clean.
The other thing is the cleanliness of that code - how will other developers feel about working with your code in the future? Right now it is not well written. As React developer, I would not expect that heavy data processing in render
method. You have class, so utilize methods (not only React lifecycle methods, but your own as well, for sake of documenting what you want to achieve) or just plain, simple and probably pure functions (if you do not need the class state).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |