What is the best way to re-render a component immediately following an update in React?

As I attempt to change the color of a bar to green and then back to black, it seems like the latter color update is taking precedence in my code.


const [color, setColor] = useState("black")
const bubbleSort = async () => {
    const sleep = ms => new Promise(res => setTimeout(res, ms));
      let len = arr.length;
      for (let i = 0; i < len; i++) {
          for (let j = 0; j < len; j++) {
              setCurrentIndex(j)
              console.log(j)
              console.log(currentIndex)
              if (arr[j] > arr[j + 1]) {
                  setColor("green")
                  console.log(color)
                  document.getElementById(`bar${j + 1}`).style.backgroundColor = color
                  let tmp = arr[j];
                  arr[j] = arr[j + 1];
                  arr[j + 1] = tmp;
                  setArr([...arr])
              }
              setColor("black")

              await sleep(200)
          }
          
      }


Answer №1

One way to achieve this functionality is by utilizing the useEffect hook.

Here's a simple implementation:

const ColorComponent = () => {
  const [color, setColor] = useState("black")

  useEffect(() => {
    if(color === "green") {
      setTimeout(function(){ 
        setColor("black");
    }, 3000); 
    }   
  }, [color, setColor])

  return <div onClick={() => setColor("green")}> HI </div>

}

The useEffect hook triggers whenever the color state changes.

In this scenario, clicking the div will change the color to green, triggering the useEffect hook which waits for 3 seconds before reverting the color back to black.

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

Does react-redux update the store value when the webpage is refreshed in a react-reducer?

While working with react-redux, I've noticed that when I refresh the webpage, the state in the reducer disappears. I'm not sure if this is an issue with my code or if it's just how reducers work in React. Are there any alternative methods to ...

What is the best way to link to a CSS file located in a different directory while being in a subdirectory?

For a project I am working on, I am developing a simple streaming site and have organized my files into different folders. These folders include: HTML CSS Shows Within the "Shows" folder, there is a subfolder named "Testshow". I am facing an issue with ...

Error Message: Undefined Constructor for Firebase Google Authentication

Hey there! I've been working on integrating Firebase google authentication into my project. Unfortunately, I encountered an error while testing it out. Here's the error message that appeared in the console: Uncaught (in promise) TypeError: Cannot ...

Strategies for displaying error messages in case of zero search results

I am currently developing a note-taking application and facing an issue with displaying error messages. The error message is being shown even when there are no search results, which is not the intended behavior. Can someone help me identify what I am doing ...

Utilizing Node.js to dynamically inject variables in SASS compilation

I am currently working on an application where I need to dynamically compile SASS before rendering it on the client side (a caching system is in the works, so no worries there). At the moment, my tool of choice is node-sass and so far, everything is runnin ...

Hover over the hidden DIV

I have a div containing an image that is overlapping multiple other divs. It looks something like this: <div style='width:100%;height:100%'><img src='someImage.png'></div> <div id='covered'>I'm un ...

Is Tailwindcss styling being automatically generated for React components that are not being used?

As I was working on optimizing the CSS bundle size for my React Project using Tailwindcss, I noticed that CSS was being generated for components that weren't even used. To test this, I created a new React Project (with Vite), installed Tailwindcss fo ...

Creating a variety of NextJS components

Currently delving into NextJS and aiming to showcase a website featuring my various projects created with it. A special "Tag" component functions as a button template that allows custom text passed through props: export default function Tag({val}) { r ...

What are some effective methods for addressing security flaws such as Regular Expression Denial of Service (Re

My react project is showing some vulnerabilities when I run it. Here is the link to image containing the vulnerability report: Can someone guide me on how to fix these vulnerabilities? Also, could you please explain what this warning means and if updating ...

Leveraging the power of NextJS: Context API for seamless storage and transmission of

I'm currently working on a project with NextJS, aiming to create a shopping cart functionality using the useContext hook. My approach was fairly straightforward - I created a ShoppingCartContext, added an addToCart function to handle pushing data to t ...

Store images securely in a private S3 bucket for access with Next.js

I am looking to access images from a private bucket instead of a public one. The code snippet below shows how I currently try to access the images, but I believe there must be a way to do so without making the entire bucket public. In my API file, I use AC ...

positioning of multiple buttons in a customized header for mui-datatables

I'm currently using mui-datatables in my app and have customized the table toolbar to include additional buttons. However, I've encountered an issue where adding a second button causes it to be displayed below the first one, despite there being e ...

Encountering the error message "TypeError: setValue is not a function" while trying to pass it as a

Struggling to update the useState() variables by receiving input from a child component nested within another child component. However, encountering an error message when attempting to call either setItem() or setValue() functions from the useState() decla ...

Updating the background of the <html> tag using jQuery

Is there a way to modify this CSS using jQuery? html { background: yellow; } Attempting the following code does not yield the desired results: $('html').css('background','red'); ...

Tips for detecting the height of a row with 2 columns in CSS

I am attempting to create two text/image boxes side by side, where one box dictates the height of both on desktop. In this scenario, the leftcol box should expand its background color to match the size of rightcol and center the content. On mobile devices, ...

Place a written message on an picture

<head> <style> .relative{position:relative; width:600px;} .absolute-text{position:absolute; bottom:1; font-size:12px; font-family:"vedana"; background:rgba(251,251,251,0.5); padding:10px 20px; width:10%; text-align:center;} </style> < ...

What are some ways I can efficiently load large background images on my website, either through lazy loading or pre

Just dipping my toes into the world of javascript. I'm currently tackling the challenge of lazy loading some large background images on my website. My goal is to have a "loading" gif displayed while the image is being loaded, similar to how it works ...

Frontend Axios request fails to retrieve necessary data from MongoDB backend database

Reaching out to the backend to retrieve posts from a mongoDB database. Successful in postman but encountering a custom error on the frontend. Puzzled as to why it's not functioning properly. Utilizing Redux to fetch user information for ...

What are the appropriate situations for utilizing getStaticPaths()?

Right now, an API call is being made in a main component and the fetched data is saved in a Singleton. This singleton data needs to be accessed by the getStaticPaths() function. However, due to the fact that getStaticPaths() pre-renders it, the singleton ...

Utilizing NextJS Image Component in Conjunction with Auth0

I have been working on integrating auth0 with nextJS and encountered an issue with the next.js Image component. Let's review the code snippet: import Image from "next/image" import { useUser } from "@auth0/nextjs-auth0" export def ...