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
Either wrap the
backgroundImages
variable withuseMemo
if you are going to generate these images dynamically in the future, if not, then move it outside the component. This way thebackgroundImages
variable will not be recreated on each render.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.