I'm using withReducer HOC and noticed this behaviour: Calling this on click handler for example:
import React from 'react'
import { withReducer } from 'recompose'
import { compose } from 'ramda'
export default compose(
withReducer('state', 'dispatch', (state, { value }) => {
console.log(value)
return { ...state, value }
}, { value: 'zero' })
)((props) => {
const { dispatch, state } = props,
onClick = () => {
console.log('Hello')
dispatch({ value: 'one' })
dispatch({ value: 'two' })
dispatch({ value: 'three' })
console.log('World')
}
return (
<div>
<div>{state.value}</div>
<button onClick={onClick}>Click me</button>
</div>
)
})
It will produce
Hello
World
one
two
three
This means that reduce function is called asynchronously. What is justification for calling it async rather than applying changes to store right away?
The reducer is called asynchronously because we can only use
setStateto update the tree andsetStateis asynchronous.If we call the reducer synchronously, we will need to save the new state somewhere, then call
setStateand get the new state asynchronously from where we save it. In the end, your tree still get updated asynchronously.This is why recompose's
withReducer()is slightly different from redux. You can think of thatwithReduceris a simplified version of redux + react-redux'sconnect().