Reaction, how to quickly update the state

What would be the recommended way to display a fast-changing value in React, for example, for loading? In my axios configuration, I have

onUploadProgress: progressEvent => { let percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ) this.setState({ avatarUploadPercentage: percentCompleted }) } 

<span>Upload progress: {this.state.avatarUploadProgress}</span>

but setState doesn't like being called so fast, and it doesn't guarantee order. Should I use refs instead and change the internal html myself?

+5
source share
3 answers

What about the restriction on the onUploadProgress ? You can include a callback in the "debounce" function, which limits the frequency of the callback. Underscore and Lodash offer debugging methods,

Once per second:

 onUploadProgress: debounce(progressEvent => { let percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ) this.setState({ avatarUploadPercentage: percentCompleted }) }, 1000) 

See the simple debounce function from https://davidwalsh.name/javascript-debounce-function .

+3
source

I would recommend using ref to access the progress element. Calling setState for this case is a bit wasteful on the rendering side if it's just a progress bar / value that is changing. Call setState when the download starts showing progress, and then setState again to hide it after it finishes.

+1
source

What do you want to do with avatarUploadPercentage ? If you need to display the actual number, then, as suggested in another answer, you can either cancel setState or change dom directly.

However, if it displays a progress bar, it can be executed using CSS, although it still modifies the element through ref, but does not start the entire component life cycle (wasteful)

Something like [refToProgressBarElement].style.width = `${avatarUploadPercentage}%`

0
source

Source: https://habr.com/ru/post/1274402/


All Articles