Structuring Redux components and containers involves organizing your code to promote reusability and maintainability.
Note: Please note that the way someone structures their Redux components and containers may vary depending on their preferences and the project's specific needs. However, a sample structure is outlined in this Answer.
Following are some protocols you may follow while structuring your Redux components and containers. We will make the modifications in the src
folder.
Create separate folders for components
and containers
to distinguish between the two.
Within the components
and containers
folder, create subfolders to group related content if needed.
|-- src/|-- components/|-- containers/
Each component/container should have its folder with an index.js
file for exporting the component and a separate style.css
(or style.js
) for styling purposes.
If a component has children components, place them within the same folder and name them accordingly.
Within the container
folder, create separate files for actions
and reducers
.
|-- src/|-- components/| |-- Incrementer/| | |-- index.js| | |-- styles.css| |-- Decrementer/| |-- index.js| |-- styles.css||-- containers|-- IncrementerContainer/| |-- index.js| |-- actions.js| |-- reducer.js| |-- styles.css|-- DecrementerContainer/|-- index.js|-- actions.js|-- reducer.js|-- styles.css
Import the necessary components to the container files.
In the index.js
file of every container, use connect()
method from the react-redux
library to connect the components to Redux store.
Map the state and dispatch functions to the components's props using mapStateToProps
and mapDispatchToProps
functions respectively.
This article provides a more comprehensive explanation of connecting components to Redux.
You can use any Redux middleware (such as redux-thunk or redux-saga) to handle asynchronous actions. Place these middlewares in a separate folder (named redux
in the following example).
|-- src/|-- components/| |-- Incrementer/| | |-- index.js| | |-- styles.css| |-- Decrementer/| |-- index.js| |-- styles.css||-- containers|-- IncrementerContainer/| |-- index.js| |-- actions.js| |-- reducer.js| |-- styles.css|-- DecrementerContainer/|-- index.js|-- actions.js|-- reducer.js|-- styles.cssredux/|-- middleware/| |-- customMiddleware.js|-- actoins/| |-- incrementAction.js| |-- decrementAction.js|-- reducers/| |-- incrementReducer.js| |-- decrementReducer.js|-- store.js
The above structure demonstrates a simplified version of a Redux-based React Application. In a real-world application, you may have more components
, containers
, and hence more actions
and reducers
.
Free Resources