I am relatively new to React, and still have not full familiarity with this thing to re-render components every time a state changes.
I understand that re-renders make declarative components possible, but in terms of performance it seems less than optimal, and I have trouble determining when component re-render is to be avoided.
Let’s say I have a render-costly component RenderCostlyComponent
with a loading
state that applies a class to it to show loading is in progress.
function RenderCostlyComponent(props) {
const [loading, setLoading] = useState(true);
const [componentData, setComponentData] = useState({});
//Data retrieval or calculation and store in 'componentData' data state
return (
<div className={loading ? 'loadingClass' : ''}>
{/*Comoponent layout here*/}
</div>
);
}
In this case, just to change a class (or in other cases where minimal changes are applied), the component needs to re-render. Surely no data has changed so React won’t rebuild the heavy DOM parts, especially if we’ve been using memoization related hooks.
But is this approach practical and production ready or this should be considered a bad practice?
2
Answers
Although the question is a bit unclear but react re-rendering process is quite a powerful feature and in most cases its impact on performance is negligible.However, if you want to optimise the code more consider:
There is a concept of component trees.
If you have a container which renders based on a state and you have a heavy content which you do not want react to visit each time your container rerenders, you can use
children
prop on container component.This way the app won’t visit when the state in Container changes.