reactjsnpmwebpack

TypeError: Cannot read properties of null (reading 'useState') while using my local react npm package


I am getting TypeError: Cannot read properties of null (reading 'useState') while using my local react npm package. My npm package built with react, typescript and bundled using webpack.

my webpack.config.json

const path = require("path");

module.exports = {
  entry: "./src/index.tsx",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "index.js",
    library: "package-name",
    libraryTarget: "umd",
    globalObject: "this",
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".jsx", ".css"],
    alias: {
      react: path.resolve(__dirname, "node_modules/react"),
      "react-dom": path.resolve(__dirname, "node_modules/react-dom"),
    },
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
      {
        test: /\.(js|jsx)$/,
        use: "babel-loader",
        exclude: /node_modules/,
      },
      {
        test: /\.module\.css$/,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              modules: true,
            },
          },
        ],
      },
    ],
  },
  externals: {
    react: {
      root: "React",
      commonjs2: "react",
      commonjs: "react",
      amd: "react",
    },
    "react-dom": {
      root: "ReactDOM",
      commonjs2: "react-dom",
      commonjs: "react-dom",
      amd: "react-dom",
    },
  },
  optimization: {
    minimize: false,
  },
  devtool: "source-map",
};

I am importing the component like this

import Component from "package-name";

I have tried lot of other combinations nothing helped so far. Please help me to finish this.


Solution

  • Finally fixed by linking the project react to my local library. The reason for this issue is having multiple react instances while installing local package.

    Duplicate React, This problem can also come up when you use npm link or an equivalent. In that case, your bundler might “see” two Reacts — one in application folder and one in your library folder. Assuming myapp and mylib are sibling folders, one possible fix is to run npm link ../myapp/node_modules/react from mylib. This should make the library use the application’s React copy.

    can see more details here - https://react.dev/warnings/invalid-hook-call-warning#duplicate-react