How to nest smart components in Redux
Smart components are the container components which connect to the Redux
Why do we need to nest components?
Nesting separate component files to structure a desirable user interface (UI) has the following advantages:
Avoid rerendering: Instead of passing down the props from the parent component to the children components, nesting allows us to connect the components avoiding any unnecessary re-rendering.
Modularity: It makes the application modular, where we can reuse the components across our codebase.
Easy debugging: Since we have a separate code for each component nested together, it would be easier to trace the exact error and debug the code.
The connect() method
You can nest Redux smart components using connect() method provided by the react-redux library. connect() is a high-order function that links each component with the Redux store to access the application's current state and dispatches actions. It also checks the conditions and decides if the container needs to be re-rendered.
Steps to achieve nesting
Note: This Answer assumes that you have already set up your react-redux application.
Let's suppose we have a three file hierarchy ParentComponent.js, ChildComponent.js, and GrandChildComponent.js as shown below:
Here's how we can use connect() method to nest them:
import { connect } from "react-redux";const ParentComponent = props => {return (<div><p>MainComponent Data {props.data}</p><ChildComponent/></div>);};const mapStateToProps = state => ({data: state.ParentComponentData});export default connect(mapStateToProps)(ParentComponent);
Line 7:
<ChildComponent/>has been nested.Line 16:
ParentComponentis being connected to the Redux store using theconnect()method.
import { connect } from "react-redux";const ChildComponent = props => {return (<div><p>ChildComponent Data {props.data}</p><GrandChildComponent/></div>);};const mapStateToProps = state => ({data: state.ChildComponentData});export default connect(mapStateToProps)(ChildComponent);
Line 7:
<GrandChildComponent/>has been nested.Line 16:
ChildComponentis being connected to the Redux store using theconnect()method.
import { connect } from "react-redux";const GrandChildComponent = props => {return (<div><p>GrandChildComponent Data {props.data}</p></div>);};const mapStateToProps = state => ({data: state.GrandChildComponent});export default connect(mapStateToProps)(GrandChildComponent);
Conclusion
As your react-redux application grows, you'll need more components to add. The flexibility of connect() allows you to nest even more smart components per your needs.
Free Resources