What would be the recommended way to display a rapidly changing value in React, e.g upload progress? In my axios config 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 that quickly of course, and won't guarantee order. Should I use refs instead and change the inner html myself?
To update state in React components, we'll use either the this. setState function or the updater function returned by the React. useState() Hook in class and function components, respectively.
Use the useEffect hook to wait for state to update in React. You can add the state variables you want to track to the hook's dependencies array and the function you pass to useEffect will run every time the state variables change.
React do not update immediately, although it seems immediate at first glance.
React will then look at the virtual DOM, it also has a copy of the old virtual DOM, that is why we shouldn't update the state directly, so we can have two different object references in memory, we have the old virtual DOM as well as the new virtual DOM.
How about limiting when the onUploadProgress
callback runs? You can wrap your callback in a "debounce" function which limits the frequency a callback will run. Underscore and Lodash offer debounce methods.
Once per second:
onUploadProgress: debounce(progressEvent => {
let percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total )
this.setState({ avatarUploadPercentage: percentCompleted })
}, 1000)
See plain debounce function from https://davidwalsh.name/javascript-debounce-function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With