Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force a re-render (update the state and update the DOM) immediately with react.js

I realize that calling setState does not update this.state immediately, nor does it immediately call render and refresh the DOM. The docs say

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

I would like to be able to force a "state transition" like this at any point. This seems like it ought to be a fairly natural operation, but I can't find any mention of it in the docs. Is there a way to do it?

like image 622
tjhance Avatar asked Jun 15 '15 06:06

tjhance


2 Answers

You can use forceUpdate for this:

If your render() method reads from something other than this.props or this.state, you'll need to tell React when it needs to re-run render() by calling forceUpdate(). You'll also need to call forceUpdate() if you mutate this.state directly.

https://facebook.github.io/react/docs/component-api.html#forceupdate

like image 195
Colin Ramsay Avatar answered Sep 18 '22 12:09

Colin Ramsay


You can use a forceUpdate in conjunction with having a key on the top level component as so..

let key= 0;

var Hello = React.createClass({

  sudoForceUpdate(){
    key++;
    this.forceUpdate();   
  },
  render: function(){
    return <div key={key}>Example</div>;
  }
});

By editing the key and forcing an update, the dom will always rerender.

Here is an example that highlights the difference between just a force edit, and one with a key change*.

https://jsfiddle.net/69z2wepo/82763/

*note that this is likely pretty bad practice.

Thanks to Ben Alpert: https://groups.google.com/forum/#!topic/reactjs/8JgClU9jol0

like image 41
lonewarrior556 Avatar answered Sep 19 '22 12:09

lonewarrior556