skip to Main Content

I have a React component that generates a background image that is random with each visit to the page. However, I do not want it to update with each rerender. This is happening now as a user types text into an input, the background image is updated each time. I have tried to use the useMemo hook without success. What am I doing wrong?

export function RegisterLayout({ children, position = 'justify-center' }) {
  return (
        ...
          <img
            src={getBackgroundImage()}
            alt=''
            className='w-100 absolute inset-0 m-auto box-border block h-0 max-h-full min-h-full w-0 min-w-full max-w-full border-none object-cover p-0'
          />
        ...
  )
}

const getBackgroundImage = () => {
  const backgroundImages = Array(backgroundImage1, backgroundImage2, backgroundImage3, backgroundImage4)
  const randomInt = Math.floor(Math.random() * backgroundImages.length)

  return backgroundImages[randomInt]
}

RegisterLayout.propTypes = {
  children: PropTypes.array,
  position: PropTypes.string
}

export default RegisterLayout

2

Answers


  1. Either wrap the backgroundImages variable with useMemo if you are going to generate these images dynamically in the future, if not, then move it outside the component. This way the backgroundImages variable will not be recreated on each render.

    Login or Signup to reply.
  2. If you want it to load a random background image only on mount I’d probably replace useMemo with useEffect, passing in an empty array as a second argument. This should prevent it from changing with each re-render.

    useEffect(() => {
      const getBackgroundImage = () => {
        const backgroundImages = Array(backgroundImage1, backgroundImage2, 
        backgroundImage3, backgroundImage4)
        const randomInt = Math.floor(Math.random()*backgroundImages.length)
        return backgroundImages[randomInt]
      }
      return (
        <img src={getBackgroundImage()} />
      )
    }, [])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search