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,
- What would be the best approach while considering the app performance ?
- Can I use same approach for
mapDispatchToProps
as well ?
Yes, you can Use
useSelector, useDispatch
but the thing is you should use hooks. It can fix considering the app performance with this approach.