Search code examples
reactjsnext.jsuse-statereact-componentnextjs-image

How to update src of <Image /> tag in NextJS without re-rendering the whole component


I want to change the image of a <Image /> tag in NextJS by updating its src with a new link, but it shows too many re-renders.

<Image
  src={itemDetails.imageUrls[0].imageUrl}
  alt="Product Image"
  layout="responsive"
  height="500"
  width="400"
/>

I want to change this src to {itemDetails.imageUrls[1].imageUrl} or {itemDetails.imageUrls[2].imageUrl} according to onClick on some other images.

I have a function to get the index of imageUrls. For example: 0, 1, 2, etc

const handleProductClick = (index) => {
  let clickedImageLink = itemDetails.imageUrls[index].imageUrl;
  setImageLink(clickedImageLink);
};

Here setImageLinkis used as a state (useState) and can be accessed using imageLink.

But when I substitute imageLink like this:

<Image
  src={imageLink}
  alt="Product Image"
  layout="responsive"
  height="500"
  width="400"
/>

This is how handleProductClick is being called:

{itemDetails.imageUrls.map((image, index) => {
    return (
       <div className="mr-2 cursor-pointer" key={index}>
       <Image
         src={image.imageUrl}
         alt="Product Image"
         height="80"
         width="70"
         onClick={() => {
         handleProductClick(index);
         }}
        />
       </div>
      );
    })}

it shows Too Many Re-renders error, like this:

enter image description here


Solution

  • This is how I did it:

      const [imageIndex, setImageIndex] = useState(0);
    
      const handleProductClick = (index) => {
          setImageIndex(index);
      };
    

    And it gets updated like this when clicked on an image:

    <Image
       src={itemDetails.imageUrls[imageIndex].imageUrl}
       alt="Product Image"
       layout="responsive"
       height="500"
       width="400"
    />