Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - render called, but DOM not updated

This has happened to me a few times. I have always managed to work around the issue, yet I am still intrigued to understand why this happens, and what I have missed.

Essentially if I have a condition within my render method which specifies the class for my div:

let divClass = this.state.renderCondition ? 'red' : 'blue';

By default I set renderCondition within my state to false.

If I then define an onClick handler on a button (as follows), and click the button, whilst render IS called, the DOM is NOT updated. That is to say the class does not change.

onClickCompile: function() {

   this.setState({renderCondition: true}, function() {

        synchronousSlowFunction();
   });
}

This seems to have something to do with running slow synchronous code in that if the code is quick and simple the DOM IS updated appropriately.

If I wrap the call to synchronousSlowFunction in a 500 millisecond timeout, everything works as expected. I would however like to understand what I have misunderstood such that I do not need this hack.

like image 611
Thomas Clowes Avatar asked Jan 05 '17 17:01

Thomas Clowes


People also ask

How do you force update the DOM in React?

Forcing an update on a React class component In any user or system event, you can call the method this. forceUpdate() , which will cause render() to be called on the component, skipping shouldComponentUpdate() , and thus, forcing React to re-evaluate the Virtual DOM and DOM state.

Why React state is not updated immediately?

The answer: They're just queues setState , and React. useState create queues for React core to update the state object of a React component. So the process to update React state is asynchronous for performance reasons. That's why changes don't feel immediate.

Is componentDidUpdate called after every render?

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render. Use this as an opportunity to operate on the DOM when the component has been updated.

Is componentDidUpdate called on first render?

ComponentDidUpdate() is invoked immediately after updating occurs and is not called for the initial render. The most common use-case for the componentDidUpdate () lifecycle method is updating the DOM in response to Prop or State changes.


1 Answers

Can you share the button onClick code? I might be wrong but this looks like an incorrectly set button onClick listener.

Make sure that onClick callback is defined without (), i.e.

<button onClick={this.something} />

instead of:

<button onClick={this.something()} />

Post more code so we can get a better (bigger) picture

like image 129
icelic Avatar answered Oct 07 '22 02:10

icelic