Search code examples
javascriptreactjsreact-nativereduxmapstatetoprops

React: Is it better to pass something as a prop to a child component, or have that child component get it from Redux?


I have components <Parent> and <Child>, and <Parent> accesses a Redux state prop called prop1 using mapStateToProps(). <Child> needs to access prop1 as well.

What's the difference between passing it to <Child> as a prop like <Child prop1={this.props.prop1}> vs having <Child> get it via mapStateToProps()? Is one way better than the other?


Solution

  • TLDR: Get it via mapStateToProps from Child

    In this simplified example you provided I would say that the best option is to get the prop1 directly in the Child component for the sake of encapsulation. It would be easier for other developers or the future you to identify the component's dependencies when it gets revisited.

    Another benefit of this approach is that it limits updates in case the prop1 changes. Only Child component will be updated in contrast to the other approach where Parent will be updated along with all of it's children.

    However there is a use-case where prop drilling from Parent may be preferred. If Child component is a reusable one and you don't want to bind it with a specific redux state slice. This way you can keep it unaware of redux and reuse it in another parent component with some other value as prop.