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

Mobile users are unable to access the form

Welcome to my website ! I encounter an issue where I can successfully submit a form on the desktop version, but it seems that the "Next" button below the form is not clickable on mobile. I would greatly appreciate any assistance in resolving this matter. ...

Having trouble with the React component "PersistLogin" during testing

I have a simple test set up: describe('App', () => { it('displays headline', async () => { render(<App />, { wrapper: BrowserRouter }); expect(screen.getByText('Welcome to Mentor Blog')).toBeInTheDocument ...

Trouble with Bootstrap 3's nav-justified feature not displaying correctly upon window expansion

Looking at this Bootstrap example page, I noticed a small issue with the nav-justified navigation. When the window is minimized, it transitions correctly to a mobile version. However, when the window is maximized again, the buttons remain in the mobile for ...

Flickity remains in plain sight on desktop devices

I am trying to hide the flickity slider on desktop and larger devices. I have followed the instructions in the documentation, but for some reason, it's not working as expected. Here is how the div looks: <div class="w-full flex pl-4 pb-16 overflo ...

Setting the value of a custom component property dynamically after the component has been rendered

I'm currently developing an Angular application and have a specific requirement to work on. I am using a custom component with 3 inputs, and I want to bind this custom component tag in the HTML of my page. <my-column [setInfo]="info" [dis ...

Exploring the Integration of Graphql Typescript Types in React Applications

I am currently working on a project that involves a React app with a Keystone.js backend and a GraphQL API. Within Keystone.js, I have a list of products and a basic GraphQL query set up like so: import gql from "graphql-tag"; export const ALL_ ...

Using CSS Flex to style text that has been transformed

I'm attempting to achieve a specific date display effect, but I'm running into some difficulties. Despite using flex and text transform, I can't seem to get rid of the extra width on the right side of the year. Here's my current outcom ...

I am puzzled as to why my DataGrid MUI component is not functioning properly

I am taking my first steps with MUI, the MaterialUI React Component library. After following the installation instructions in the documentation, I am now attempting to integrate the DataGrid component into my React project. My goal is to replicate the fir ...

Homepage featuring a stacked image background similar to Kickstarter

I am trying to replicate the stacked image effect seen on kickstarter.com. However, I am facing an issue where the images do not overflow on the screen as desired. The arrow indicates the area that needs to be filled with the image. Check out the image he ...

Adjust the size of icon passed as props in React

Below is the component I am working on: import ListItemButton from '@mui/material/ListItemButton'; import ListItemIcon from '@mui/material/ListItemIcon'; import Tooltip from '@mui/material/Tooltip'; const MenuItem = ({data, o ...

Is it possible to customize the Menu hover effect in Element Plus and Vue?

Hello everyone, I'm a beginner with Vue, HTML, CSS, and Element Plus. I am trying to customize a Side Bar Menu with my own hover effect, but it doesn't seem to be working. Whenever I change the background color of the el-menu element, the hover e ...

Execute script when on a specific webpage AND navigating away from another specific webpage

I created a CSS code that adds a fade-in effect to the title of my website, and it works perfectly. However, I now want to customize the fade-in and fade-out effect based on the page I am transitioning from. My desired outcome: If I am leaving the "Biolo ...

Bring a div box to life using AngularJS

Struggling to animate a div-Box in AngularJS? Despite trying multiple examples, the animation just won't cooperate. I'm aiming to implement a feature where clicking on a button triggers a transition animation to display the search form. I under ...

Using Jquery to toggle a class on click, and dynamically change based on the screen size

I am trying to figure out how to toggle a CSS class on an element by clicking on a div using jQuery. I know how to do it, but I also want the toggle to only happen when the screen size is less than 800px. I'm not very familiar with JavaScript, so I co ...

Discovering the various types of options for ReactJs PropTypes

When working with the Component below, I am interested in adding more ReactPropTypes but not sure about my choices. var ContactItem = React.createClass({ propTypes: { name: ReactPropTypes.string, number: ReactPropTypes.????? } )} Can you sugg ...

Stylish grey container with crisp white lettering

Just getting started with HTML and I've been working on a project for my class. Here's what I've come up with: <font style="background-color: grey; color: white; display: block">Black and white copies $.10 per page letter/legal size&l ...

Caution: A value of `true` was passed for a non-Boolean attribute `error`

While creating a component and its stories in Storybook for React, I keep encountering an error message intermittently: The issue seems to be originating from this part of the code inside the component. It appears that removing {...props} from the input e ...

custom field component for react-hook-form

I have been working on creating a form field component that can be utilized at both the root form level and as a nested field. export type FirstNameField = { firstName: string; }; type GenericFormType<T, NS extends string | never = never> = NS ext ...

What is the correct way to update the state of an object in ReactJS using Redux?

Hello, I am facing an issue with storing input field values in the state object named 'userInfo'. Here is what my code looks like: <TextField onChange={this.handleUserUsername.bind(this)} value={this.props.userInfo.username} /> ...

Troubleshooting: Why is the child component not updating when the parent state changes in

Within the example presented below, the Apps (parent) component and its child components load successfully upon startup. However, when selecting a tab (triggering handleClick) that updates the state with a new tab value, the child components (tabs, conte ...