Skip to content
This repository was archived by the owner on Nov 10, 2021. It is now read-only.
This repository was archived by the owner on Nov 10, 2021. It is now read-only.

[Question] Why multi store subscriptions? #33

Closed
@hnordt

Description

@hnordt

Just for curiosity, why you've opted for a multi-store subscription model instead of subscribing to the store in a top-level Provider?

Something like:

const ReduxStateContext = React.createContext()

function ReduxStateProvider({ store, children }) {
  const [state, setState] = React.useState(() => store.getState())

  useEffect(() => {
    let willUnsubscribe = false

    const checkForUpdates = () => {
      if (willUnsubscribe) return

      setState(prevState => {
        const nextState = store.getState()
        return shallowEqual(prevState, nextState) ? prevState : nextState
      })
    }

    checkForUpdates()

    const unsubscribe = store.subscribe(checkForUpdates)

    return () => {
      willUnsubscribe = true
      unsubscribe()
    }
  }, [store])

  return (
    <ReduxStateContext.Provider value={state}>
      {children}
    </ReduxStateContext.Provider>
  )
}

export function useMappedState(mapState) {
  const state = useContext(ReduxStateContext)

  const [derivedState, setDerivedState] = useState(() => mapState(state))

  useEffect(() => {
    setDerivedState(prevDerivedState => {
      const nextDerivedState = mapState(state)
      return shallowEqual(prevDerivedState, nextDerivedState)
        ? prevDerivedState
        : nextDerivedState
    })
  }, [state])

  // It might not even need useEffect() 🤔 (getDerivedStateFromProps)
  setDerivedState(prevDerivedState => {
    const nextDerivedState = mapState(state)
    return shallowEqual(prevDerivedState, nextDerivedState)
      ? prevDerivedState
      : nextDerivedState
  })

  return derivedState
}

Only the ReduxStateProvider subscribes to store updates, then it passes the update down to all consumers. Consumers have a chance to bail out by comparing prevDerivedState with nextDerivedState.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions