Dynamically show an image when loads in React

Apr 25, 2020

Little snippet on how to load an image when the source it's loaded:

The new instance of the image loads the source of the image that we want, then we attach a function to the load event, when this one loads we set show to true and we show the div containing the img in the DOM, so when the actual img ask for the source it's already loaded.

import React, { useState, useEffect } from 'react'

const ImgComp = (props) => {
  const [show, setShow] = useState(false)

  useEffect(() => {
    let img = new Image()
    img.src = props.url
    
    // Preloads the img
    img.onload = () => {
      setShow(true)
      img = null;
    }
  }, [])
  
  // Shows the div when image is loaded
  return (
    <div style={{display: show ? 'block' : 'none'}}>
  	  <img src={props.url} alt="Awesome photo" />
    </div>
  )	
}

The part Ā img = null i'm not sure if it does something but the idea is to set the img to null so that the garbage collector deletes the new instance of the image that it's used for loading the src.

Ramiro

Hey hi! My name is Ramiro, this is my blog about artificial intelligence, coding and things that are in my head. Follow me on twitter @ramgendeploy so we can chat!

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.