Skip to content
Advertisement

How to re-render a component on each of multiple state changes?

I’m still learning JS/React, so it’s likely I’m doing this completely wrong. Any criticism is welcome.

I have a Canvas with a drawning on it. I want to change the color of the drawning multiple times when a button is pressed. To be clear: I want a single click on the button to change the color of the drawning multiple times.

I’ve tried doing this a few different ways, but they are mosly variations of two:

  • When the button is pressed, it calls the method that will change the state multiple times, but React only bothers to render the last state I set. (Which makes sense)

  • Using setTimeout for each setState, but it seems it breaks the method, and the render never changes.

Here is a sample code:

JavaScript

What I’m doing wrong and how can I achieve the multiple color changes with react?

Advertisement

Answer

Without setTimeout all the renders will be basically merged into one, this is how React works. However you could try setTimeout with a dynamic timeout.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement