Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React, how to update state fast

Tags:

reactjs

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?

like image 244
Titan Avatar asked Dec 30 '17 21:12

Titan


People also ask

How do you update state immediately in React?

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.

How wait for state to update React?

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.

Does React useState hook update immediately?

React do not update immediately, although it seems immediate at first glance.

Can you update state directly React?

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.


1 Answers

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.

like image 64
skylerfenn Avatar answered Oct 19 '22 10:10

skylerfenn