SetState() is not the same function in Reflux and React!

I remember moving some functions from a local component into a store, and it quit working. When I figured out the problem, I ended up reverse engineering some of the Reflux NPM package source to see why it was happening. The differences are:

  • setState in Reflux WILL NOT take a callback function as a second argument
  • setState in Reflux WILL NOT properly merge nested keys – it just overwrites at whatever level you give it
  • setState in Reflux WILL NOT get batched into multiple updates like React does – it does still work async (from what I can tell), but not in intelligent batching

All of those things that Reflux does not do, React does do in its version of setState()

React:

(constructor)
this.state = {
foo: ‘string foo’,
bar: {
baz: ‘string baz’,
baz2: ‘string baz2’,
}
}

…then stuff happens…

this.setState({
bar: {
baz: ‘string baz CHANGED’,
}
})

Results in an object that looks like:

this.state = {
foo: ‘string foo’,
bar: {
baz: ‘string baz CHANGED’,
                                baz2: ‘string baz2’,
}

React’s setState applied a DIFFERENCE between the two “bar” objects (current and new), and merged them

Compared with Reflux:

(constructor)

this.state = {
foo: ‘string foo’,
bar: {
baz: ‘string baz’,
baz2: ‘string baz2’,
}
}

…then reflux action happens…

this.setState({
bar: {
baz: ‘string baz CHANGED’,
}
})

which results in:

this.state = {
foo: ‘string foo’,
bar: {
baz: ‘string baz CHANGED’,
baz2: ‘string baz2’,   (this key gets deleted because the setstate for “bar” above only has “baz” in it)
                }

Reflux’s setState applied a DIRECT KEY SET on the object “bar”, and overwrote it, instead of merging! This can completely drop things inside of a nested object.