redux-transient icon indicating copy to clipboard operation
redux-transient copied to clipboard

What happens if multiple components `withReducer(reducer)` with the same reducer function?

Open limscoder opened this issue 7 years ago • 2 comments

If 2 components register the same temporary reducer function will the reducer function get called twice for every dispatched action or only once?

limscoder avatar May 31 '17 20:05 limscoder

Good question. Behind the scenes this withReducer HoC dispatches addReducer and removeReducer actions upon componentDifMount and componentWillUnmount respectively. When adding a resolver function, the transientEnhancer compares existing reducers with an equality check using indexOf. Therefore, if the function being added in both withReducer calls are identical, than they won't get added twice. The problem is that the first to component to unmount will disconect the reducer. This is definitely a bug.

Related: The action addReducer accepts an extra argument called allowRepeated, which defaults to false. When set to true, is won't compare the reducer with the existing ones and will effectively add a repeated transient reducer. Similarly, removeReducer action accepts removeRepeated, which would remove any occurrence of a given reducer.

@limscoder I believe there is much room for improvement here, but I wouldn't put much effort for things people don't find useful.

  • Reducers added without allowRepeated should record a count of usage. They should get removed once the count reaches zero;
  • Reducers should be identified (by index, maybe?) so that they can be removed in the same order they were added/
  • withReducer should accept a second optional argument to give access to the low level API. Probably, a function receiving the provided reducer (and props, may be?) and returning an action would fit most needs.
// Example reducer
import { withReducer, addReducer } from `redux-transient`

const transient = state => ++state

withReducer(transient, reducer => addReducer({ reducer, allowRepeated: true }))

Could you explain me a situation of yours that would need the same reducer being add twice with withReducer? And if so, do you think you can file a pull-request with the implementation of the third item in the above list?

lucasconstantino avatar May 31 '17 20:05 lucasconstantino

Use case is 2 different asynchronously loaded components that use the same reducer.

We're just exploring at this point. Will certainly consider PR if we use this package and need this feature.

limscoder avatar Jun 01 '17 15:06 limscoder