Background image changing due to React re-render

I'm working on a React component that generates a random background image each time a user visits the page. However, I'm facing an issue where the background image updates every time a user types something into an input field. I've tried using the useMemo hook to prevent this behavior but it's not working as expected. Can someone help me identify what I might be doing wrong?

export function RegisterLayout({ children, position = 'justify-center' }) {
  return (
        ...
          <img
            src={getRandomBackgroundImage()}
            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 getRandomBackgroundImage = () => {
  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

Answer №1

To load a random background image only upon mounting, consider replacing useMemo with useEffect and include an empty array as the second argument. This will ensure that the image does not change with each re-render.

useEffect(() => {
  const getBackgroundImage = () => {
    const backgrounds = Array(backgroundImage1, backgroundImage2, 
    backgroundImage3, backgroundImage4)
    const randIndex = Math.floor(Math.random()*backgrounds.length)
    return backgrounds[randIndex]
  }
  
  return (
    <img src={getBackgroundImage()} />
  )
}, [])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Designing a menu header against a specific background color resulting in misalignment

I have been working on creating a menu header for my website. If you would like to take a look, here is the link to my jsfiddle page. Unfortunately, I am facing an issue where all my images and text should remain in that grey color scheme but somehow it& ...

Subclass Pseudoclass in JavaFX is a powerful feature that

I wanted to create two different styles of buttons in one css file. To achieve this, I added a class to the second button using: close.getStyleClass().add("close-button"); Now, I can reference this button in the css by: .button.close-button However, I ...

What is the best way to create a smooth transition for a bootstrap navbar in chrome, toggling from right to left on

I have successfully modified the bootstrap navbar to toggle from right to left instead of top to bottom using the following code: For HTML- <nav class="navbar navbar-inverse" role="navigation" style="height: 55px; padding-top: 2px; background-color: # ...

I'm currently facing an issue with my webpack.config.js file

Issue with configuration object. Webpack was initialized using a config that does not match the API schema. - configuration.module.rules[0] has an unknown property 'option'. Valid properties include: object { compiler?, enforce?, exclude?, in ...

Proper syntax for SVG props in JSX

I have developed a small React component that primarily consists of an SVG being returned. My goal is to pass a fill color to the React component and have the SVG use this color. When calling the SVG component, I do so like this: <Icon fillColour="#f ...

Button styles that have been verified will not be shown in Firefox

Hello, first time poster here! Client specifications for CSS: button { border: 1px solid #B8B7B8; border-radius: 8px; height: 4em; margin: 25px 2px 25px 0; text-align: center; text-decoration: none; width: 4em; } button:active, button:che ...

Hey there, I was wondering if it's possible to modify the color of the navbar when scrolling on a specific page

After the first 3 pages with a black background and a transparent navbar with white navigation items, I encounter visibility issues when scrolling to the colorful 4th page. Is there a way to change the navbar color on this specific page using ONLY HTML a ...

Is it possible to utilize a Node.js server along with Mongoose to save the current time every second, then transmit that time in milliseconds to the client upon refreshing the page?

Currently, I am developing a food expiration tracking application. The issue I am facing is that when food items are added to the app, a timer begins counting down. However, upon refreshing the page, the timer restarts from the beginning. To combat this pr ...

React, redux, and redux observable are all essential tools for developing web applications. They

I am currently working on determining the type of a promise's resolve function. Here is a snippet of the code, or you can find it on GitHub: https://github.com/Electra-project/Electra-Desktop/blob/master/src/app/header/epics.ts export function getSt ...

The functionality of nested routing is not operating properly in react-router

I'm currently struggling to get my CollectionPage to render and match the URL correctly within my nested Route in React. Unfortunately, it doesn't seem to be working as expected! Here's a piece of code from my shop.component file that is be ...

rearranging the positioning of links in the HTML navbar

Is there a way to prevent other links in the navbar from moving up slightly when hovering over one link and creating a line (border bottom)? ` .n24{ margin-top: 2px; padding: 14px 14px; } .n25{ margin-top: 2px; padding: 14px 14px; } . ...

Issues encountered while developing a ReactJS application using TypeScript

While attempting to create a React app using the command npx create-react-app client-app --use-npm --typescript, I expected to generate a project with TypeScript files, but instead ended up with index.js and app.js rather than index.tsx and app.tsx. Could ...

Error: The variable "dispatcher.useMemo" is not recognized as an object

I encountered an issue while trying to incorporate InversifyJS with MobX in my React Native project. The error message I received was: ERROR TypeError: null is not an object (evaluating 'dispatcher.useMemo') Surprisingly, I have not utilized ...

The layout of the divs becomes distorted when the window is resized

When adjusting the window size, all elements in the center become cramped and unresponsive. Even the navigation items in the header do not resize properly. Here is my Triangle.js file: import React from 'react' import { motion } from 'fram ...

An error was encountered in the index.js file within the app directory when running the webpack

Recently, I was told to learn react.js even though my knowledge of javascript is limited. Nevertheless, I decided to dive in and start with a simple "Hello World" project. Initially, when I used the index.js file below and ran webpack -p, everything worke ...

Hide the popup by clicking anywhere outside of it

I need help with a code that involves a button triggering a popup, and I want the user to be able to close the popup by clicking outside of it when it's open. My goal is to assign the method "Close()" to the event listener that detects clicks outside ...

Pictures failing to load in a Next.js application following deployment on Vercel

Currently, I am integrating the tmdb movie API into my website using Next.js and the getServerSideProps method to fetch data. While everything works perfectly on localhost, once I deploy the site on Vercel, the images fail to load correctly. The URL appea ...

Uncovering the Depths of React Native Background Services

While using Firebase, I want my app to push notifications when new data is added to the database while it's in the background. Currently, I've implemented the following code: message.on('child_added', function(data) { pushNotificatio ...

Enhance your Divi theme with Elegant Themes: Explore mobile-friendly background image zoom effects

I have a regular section module with an image as the background. The design looks great on desktop but appears zoomed in and blurry on mobile devices. I'm struggling to understand why the mobile view is not adjusting properly, and I am unsure if there ...

Placing the image at the lower edge of the page

Looking to display thumbnails in a div with dimensions of 120x120, but struggling with the vertical alignment. The current image size is 120x57 and it's not aligning properly within the div, leaving too much space at the top. Here is the code snippet ...