How to Structure Redux Components and Containers
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.
Protocols
Following are some protocols you may follow while structuring your Redux components and containers. We will make the modifications in the src folder.
Folder structure
Create separate folders for
componentsandcontainersto distinguish between the two.Within the
componentsandcontainersfolder, create subfolders to group related content if needed.
|-- src/|-- components/|-- containers/
Components and Containers structure
Each component/container should have its folder with an
index.jsfile for exporting the component and a separatestyle.css(orstyle.js) for styling purposes.If a component has children components, place them within the same folder and name them accordingly.
Within the
containerfolder, create separate files foractionsandreducers.
|-- 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
Connect components to Redux
Import the necessary components to the container files.
In the
index.jsfile of every container, useconnect()method from thereact-reduxlibrary to connect the components to Redux store.Map the state and dispatch functions to the components's props using
mapStateToPropsandmapDispatchToPropsfunctions respectively.
This article provides a more comprehensive explanation of connecting components to Redux.
Redux middleware
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
Conclusion
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