Next.js Discord

Discord Forum

How to change prop of component without it re-rendering?

Unanswered
Forest yellowjacket posted this in #help-forum
Open in Discord
Forest yellowjacketOP
This is not necessarily NextJS-specific but more React, but perhaps there is a NextJS solution. Not sure.

I have a component in my app where you can interact with it to resize the component. Just picture like a square or something you can resize.

How do I keep the component from constantly re-rendering itself when being resized? It seems unnecessary. Maybe I don't understand React enough though. Does the component have to be re-rendered in the DOM when it's resized?

5 Replies

In React (including Next.js), when you resize a component, it will re-render.
That is why the state or props controlling its size likely change, causing the component to update.
But you can reduce unneccessary re-renders.
You can store the size in a useref instead of useState.useRef doesn't trigger re-renders when uploaded.
You can refer this code:
import { useRef } from 'react'; function ResizableComponent() { const sizeRef = useRef({ width: 100, height: 100 }); const handleResize = (newWidth, newHeight) => { sizeRef.current = { width: newWidth, height: newHeight }; // Apply the new size directly to the DOM or CSS class if necessary }; return ( <div style={{ width: sizeRef.current.width, height: sizeRef.current.height }}> {/* Resize controls go here */} </div> ); }
Forest yellowjacketOP
Thank you. So there is something I'm trying to understand. I have 2 elements next to eachother in a Flexbox layout. When one resizes, technically so does the other. So when I resize one of these elements how I described above, it causes it to re-render. But the 2nd element that is next to it in the flexbox, doesn't appear to re-render when this happens, even though it's size is clearly changing. Can you explain this?