vince vince - 3 months ago 11
React JSX Question

is it ok to wrap similarly connected components in the same HoC instead of having them all connect() the same way to the auth reducer?

A few of my components are only connected to the auth reducer, for the only reason that they need to know if the user is authenticated/logged or not.
I created an higher order component (withAuth) to wrap those components (and add the isLogged prop), but I do not know if it is a good pattern or not.

ps - the described use case was simplified, there are a couple more properties/actions mapped that way.

Thanks for the help!

Edit - here is some code to illustrate: let's pretend we have a few widgets sharing that code (add a few mapped actions, props, etc)

import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { getIsLogged } from 'authManager/reducer'

const Widget1 = props => {
return <div>{props.isLogged ? 'yay!' : 'nope'}</div>
}

Widget1.propTypes = {
isLogged: PropTypes.bool.isRequired
}

const mapStateToProps = (state) => {
return {
isLogged: getIsLogged(state)
}
}

export default connect(
mapStateToProps
)(Widget1)


I just refactored creating the following HoC

import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { getIsLogged, getFirstName } from 'authManager/reducer'

const withAuth = ComposedComponent => {
class _hoc extends React.Component {
render () {
return <ComposedComponent {...this.props} />
}
}

_hoc.propTypes = {
isLogged: PropTypes.bool.isRequired,
firstName: PropTypes.string
}

const mapStateToProps = (state, {params}) => {
return {
isLogged: getIsLogged(state),
firstName: getFirstName(state)
}
}

return connect(
mapStateToProps
)(_hoc)
}

export default withAuth


And now all the previous widgets look like this:

import React, { PropTypes } from 'react'
import withAuth from 'hoc/withAuth'

const Widget1 = props => {
return <div>{props.isLogged ? 'yay!' : 'nope'}</div>
}

Widget1.propTypes = {
isLogged: PropTypes.bool.isRequired
}

export default withAuth(Widget1)


I start wondering if there is something I am doing wrong with connected component/containers, and that what that HoC should be (or is?).

Anyway, the question stands: is that a good move or not?

Answer

Your code is totally fine. The idiomatic way to connect your component is to connect those that are the most "closer" to the data they need. Creating a HoC withAuth is definitively a good way to go. You don't have to worry to much about the number of connected components in your app since the complexity for the pub/sub pattern is O(n) with n the number of connected components. Since it's very unlikely you have thousands of them, dealing with many HoC that connect to the store isn't too much of a big deal.

Comments