Today Icelab Learned
 about react

In React setState is not "guaranteed" to be synchronous.

I discovered recently that if you do something link this in react:

this.setState({reallyUseful: true})

if (this.state.reallyUseful) {
  this.doSomethingAmazing()
}

… it’s not very useful and more often than not nothing amazing happens, just confusion and sadness.

This is because setState it turns out, is asynchronous. Of course most of the time you are doing your amazing things in your render function so everything is sweet but on the odd occasion that you need to pass that value elsewhere, eg: publishing an event, beware!

From the docs:

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.

Read about setState here.

Editor’s note — setState will also take a callback as its second argument that’ll be executed after this.state has been updated:

this.setState(
  { reallyUseful: true },
  function() {
    if (this.state.reallyUseful) {
      this.doSomethingAmazing()
    }
  }
)

Using namespaced components in React

The last time I used React we had some pretty awkward workarounds for the fact that components couldn’t be namespaced. I was pretty stoked to find this has been fixed now.

So if you have a component myNavComponent you can do:

var NavComponent = React.createClass(...);

Define your sub-components as attributes:

NavComponent.Next = React.createClass(...);
NavComponent.Prev = React.createClass(...);
NavComponent.Goto = React.createClass(...);
var Nav = NavComponent;

And then use them as you would expect to in your JSX:

<Nav>
  <Nav.Prev />
  <Nav.Goto />
  <Nav.Next />
</Nav>

https://facebook.github.io/react/docs/jsx-in-depth.html#namespaced-components