In React projects, we usually use Redux to manage the global state of the application. In this case, we need to encapsulate the store, reducer, and action to achieve elegant and efficient state management.
Here are the strategies and recommendations for encapsulating the store, reducer, and action files:
-
Create folder structure: To maintain code readability and maintainability, create a folder named "store" in the project. Inside the "store" folder, create the following files and folders:
- actions (folder)
- reducers (folder)
- index.js (file)
-
Write actions: In the actions folder, create a separate file for each feature module. In these files, we define actions for different operations.
For example, if we have a user module, we can create a file named "user.js" in the /actions folder.// actions/user.js export const updateUser = (user) => ({ type: "UPDATE_USER", payload: user }); export const removeUser = () => ({ type: "REMOVE_USER" });
-
Write reducers: In the reducers folder, create a separate file for each feature module. In these files, we define reducers that respond to different actions. By breaking down the feature modules into different files, we can easily track and maintain them.
For example, create a file named "user.js" in the /reducers folder.// reducers/user.js const initialState = { user: null }; export const userReducer = (state = initialState, action) => { switch (action.type) { case "UPDATE_USER": return { ...state, ...action.payload }; case "REMOVE_USER": return { ...state, user: null }; default: return state; } };
-
Combine reducers: In the reducers folder, create a file named "index.js" and import all the reducers. Use the combineReducers method to combine them into a root reducer.
// reducers/index.js import { combineReducers } from "redux"; import { userReducer } from "./user"; export default combineReducers({ user: userReducer, // Add other reducers here if needed });
-
Configure the store: In the "index.js" file inside the store folder, configure and export the store. Here, import the root reducer and use the createStore method to create the store.
// store/index.js import { createStore } from "redux"; import rootReducer from "./reducers"; const store = createStore(rootReducer); export default store;
-
Use the Provider in the top-level component (usually index.js or app.js) to pass the store to the React component tree.
// index.js or app.js import React from "react"; import ReactDOM from "react-dom"; import { Provider } from "react-redux"; import store from "./store"; import App from "./App"; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById("root") );
Now, we have completed the encapsulation of the store, reducer, and action. You can adjust and expand them according to the requirements of your project.