Smart components are the container components which connect to the Redux
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.
connect()
methodYou 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.
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: ParentComponent
is being connected to the Redux store using the connect()
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: ChildComponent
is being connected to the Redux store using the connect()
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);
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