0

I'm creating react native app with redux state management. I want to know what is the best practice of having connect(mapStateToProps, mapDispatchToProps).

I have several component classes i.e. ParentA, ChildA, ChildB. Currently I'm getting state properties for each parent and child classes independently.

eg:

const ParentA = (props) => {
  return (
    <View>
      <Text>{props.item.name}</Text>
      <ChildA />
      <ChildB />
    </View>
  )
}

const mapStateToProps = (state) => {
  const { item } = state

  return {
    item: item.item,
  }
}

export default connect(mapStateToProps)(ParentA)
const ChildA = (props) => {
  return (
    <View>
      <Text>{props.item.name}</Text>
    </View>
  )
}

const mapStateToProps = (state) => {
  const { item } = state

  return {
    item: item.item,
  }
}

export default connect(mapStateToProps)(ChildA)
const ChildB = (props) => {
  return (
    <View>
      <Text>{props.item.age}</Text>
    </View>
  )
}

const mapStateToProps = (state) => {
  const { item } = state

  return {
    item: item.item,
  }
}

export default connect(mapStateToProps)(ChildB)

But rather having connect for each child component I could get item state from ParentA and pass it to Child components.

eg:

const ParentA = (props) => {
  return (
    <View>
      <Text>{props.item.name}</Text>
      <ChildA item={item}/>
      <ChildB item={item}/>
    </View>
  )
}

const mapStateToProps = (state) => {
  const { item } = state

  return {
    item: item.item,
  }
}

export default connect(mapStateToProps)(ParentA)
const ChildA = (props) => {
  return (
    <View>
      <Text>{props.item.name}</Text>
    </View>
  )
}

const mapStateToProps = (state) => {
  const { item } = state

  return {
    item: item.item,
  }
}

export default ChildA
const ChildB = (props) => {
  return (
    <View>
      <Text>{props.item.age}</Text>
    </View>
  )
}

const mapStateToProps = (state) => {
  const { item } = state

  return {
    item: item.item,
  }
}

export default ChildB

My questions are,

  1. What would be the best approach while considering the app performance ?
  2. Can I use same approach for mapDispatchToProps as well ?
John Stuart
  • 950
  • 5
  • 11
  • 28
  • 1
    Feel to free you can read about it here : https://www.samdawson.dev/article/react-redux-use-selector-vs-connect – zidniryi Jun 05 '21 at 07:00

2 Answers2

1

Yes, you can Use useSelector, useDispatch but the thing is you should use hooks. It can fix considering the app performance with this approach.

zidniryi
  • 1,212
  • 3
  • 15
  • 36
1

I think rather than using 'const', try another datatypes such as 'var' or 'let' as 'const' value once fixed cannot be changed.

Assaulter_OO7
  • 11
  • 2
  • 5