React native app performance on connect(mapStateToProps, mapDispatchToProps)

68 Views Asked by At

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 ?
2

There are 2 best solutions below

0
On

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

0
On

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