How to access Redux store in the React library from Parent Application

Sakshi Mahajan
3 min readDec 30, 2021

Problem statement:

While accessing the redux store and react-redux hooks (such as useDispatch and useSelector) in the react library, I got an error “wrap component in the Provider” because the redux store is not reachable which is already declared in the react application.

The aim was to create a react library that can share redux-store created within the react application.

Solution:

After exploring lots of GitHub issues and StackOverflow posts finally, one approach worked well for me:

The approach was to create a webpack react library thereafter importing react-redux from externals in the webpack config file and connecting the functional component to redux at the end.

Let’s implement this approach with code from scratch and access the Redux store or you can have a look at the Git repo.

  1. Create a folder for the library and In the terminal move to the folder location.

2. To create a package.json file in the folder

Add details for the package by answering questions:

3. Next, add basic dependencies for the project. List of dependencies:

4. Create a new file named webpack.config.js with details as follows:

const path = require('path');module.exports = {entry: "./src/index.js",module: {rules: [{test: /\.m?js$/,exclude: /node_modules/,use: {loader: "babel-loader"}}]},externals: {reactRedux: 'react-redux',react: 'react'},output: {filename: "index.js",path: path.resolve(__dirname, "dist"),libraryTarget: "umd",library: "router"}};

5. Create a new file .babelrc to enable jsx format.

{“presets”: [“@babel/preset-env”,”@babel/preset-react”],“plugins”: [[“@babel/plugin-proposal-class-properties”, { “loose”: false }]]}

6. add scripts to your package.json

“start”: “webpack-dev-server — mode=development — open — hot”,“build”: “webpack — mode=production”

And update main to:

“main”: “dist/index.js”,

7. Create an src folder to add relevant files. Here is what your folder structure looks like:

8. After adding the required code let’s build our library to import it into the application.

9. Add all actions and types you want to access in the library already declared in the react application reducer file for state management.

After that you will be able to access your store in the webpack library and in your application as well sharing them will ease your work.

Thanks for reading!!

For any query please feel free to add in comments…hope will help you to solve this issue.

--

--

Sakshi Mahajan

React Developer | Frontend Developer | Data Science Enthusiast