Issue: The zoom functionality in my React application becomes sluggish when I have over 20 components rendered. The app needs to handle zooming with thousands of components being rendered.
Current zoom implementation:
Currently, in my application, there is a parent component that includes a zoom feature which listens for the onWheel
event and updates a zoomFactor
variable using the useState
hook.
Each child component of the parent accesses the zoomFactor
using useContext
. This means that whenever the zoomFactor
changes, the child component receives this update and adjusts its dimensions (such as offsetX
and width
) by multiplying them with the updated zoomFactor
to get a zoomAdjustedOffsetX
and zoomAdjustedWidth
.
These adjusted values are then included in a styles object:
const styles = {
transform: 'translateX(' + zoomAdjustedOffsetX + 'px)',
width: zoomAdjustedWidth + 'px',
}
This styles object is then passed inline to the returned component.
The performance issue seems to be coming from re-rendering all components during each zoom step. However, there is no need to re-render all the components, just to update two CSS properties during the onWheel event to reflect the updated zoomFactor
.
Proposed solution to improve performance:
In the parent component, maintain a reference to an object that maps the
ID
of each child component to its respective component reference.During the
onWheel
event, iterate through this map and manually update the CSS of each child component with the newzoomFactor
.
While this approach may not be the conventional "React way" of doing things, it seems necessary to achieve the desired zoom effect without slowing down the application by re-rendering everything.
My question: Will this approach lead to performance improvements? Are there any other strategies to manipulate the CSS of thousands of components during an onWheel
event to achieve a smooth 'zooming' effect?