Suraj A J
Suraj A J

Reputation: 359

Usage of recoil in custom NPM component

I'm trying to use recoil in a custom npm component so that I can publish and use it in an application but upon usage getting error as below:

Invalid hook call. Hooks can only be called inside of the body of a function component...

> const useStoreRef = () => useContext(AppContext);

I'm using following rollupjs to build package:

rollup.config.js

import babel from "@rollup/plugin-babel";
import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
import external from "rollup-plugin-peer-deps-external";
import postcss from "rollup-plugin-postcss";
import postcssImport from "postcss-import";
import packageJSON from "./package.json";

const input = "./src/index.js";

const PLUGINS = [
  babel({
    exclude: "node_modules/**",
  }),
  external(),
  resolve({
    jsnext: true,
    main: true,
    browser: true,
  }),
  commonjs(),
  postcss({
    plugins: [postcssImport()],
  }),
];

export default [
  // CommonJS
  {
    input,
    output: {
      file: packageJSON.main,
      format: "cjs",
      sourcemap: true,
    },
    plugins: PLUGINS,
  },
];

.babelrc

{
    "presets": ["@babel/preset-env", "@babel/preset-react"],
    "plugins": ["@babel/plugin-proposal-class-properties"]
}

src/index.js

import React, { useEffect, useState, useCallback } from "react";
import { useRecoilState, useSetRecoilState } from "recoil";
import {atomState} from '../recoil/atom';

const Component = () => {
    const [state, setState] = useRecoilState(atomState);

    ...
    ...

    return <div>
        ...
        {state}
        ...
    </div>
}

In application, the published component is used as below:

App.js

import {Component} from "NPM_PACKAGE_NAME";
import {RecoilRoot} from "recoil";

<RecoilRoot>
    <Component />
</RecoilRoot>

Please help resolve this. I'm new to recoil js. Thanks in advance.

Note: I'm using yarn link to use the package

Upvotes: 0

Views: 426

Answers (1)

Suraj A J
Suraj A J

Reputation: 359

I saw a few GitHub issues on this. Apparently this problem exists only if you are using yarn link to use package in your application. If I am publishing to npm registry and use, it works as expected.

Upvotes: 1

Related Questions