tsdx: Can't use hooks when `react` & `react-dom` are dev dependencies

Current Behavior

Thank you for this project!

I’m not sure if I missed or didn’t understand something, but when choosing the react template, react & react-dom are added as dev dependencies. When you then try to use a hook inside your library, you get a react-invalid-hook-call error. It works fine when removing them as dev dependencies and running yarn again.

Example:

export const Thing = () => {
  const [fooBar, setFooBar] = React.useState('foo');

  return (
    <div onClick={() => setFooBar('bar')}>
      the snozzberries taste like {fooBar}
    </div>
  );
};

Expected behavior

I would expect the template to enable me to use hooks.

Suggested solution(s)

No idea if “just removing the dev dependencies” is the proper solution. It at least worked for me.

Your environment

Software Version(s)
TSDX 0.5.4
TypeScript 3.4.5
Browser Chrome 74.0.3729.108
npm/Yarn Yarn 1.12.3
Operating System MacOS 10.14.4

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 1
  • Comments: 16 (4 by maintainers)

Commits related to this issue

Most upvoted comments

I think I found the problem. I was testing it using yarn link and I couldn’t get it to work without removing the devDependency. Publishing a package based on 0.5.5 and using that worked fine. Thanks you all!

This doesn’t work if you’re trying to deploy the example site to Netlify or something similar. Is there any other way to accomplish this?

made a PR to do just that

I think the solution I like best now is to use Parcel’s alias like so:

  "name": "example",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "parcel index.html"
  },
  "dependencies": {
    "react-app-polyfill": "^1.0.0"
  },
  "alias": {
    "react": "../node_modules/react",
    "react-dom": "../node_modules/react-dom"
  },

  "devDependencies": {
    "@types/react": "^16.8.15",
    "@types/react-dom": "^16.8.4",
    "parcel": "^1.12.3",
    "typescript": "^3.4.5"
  }
}```

Facing the same problem; I don’t think it is caused by tsdx itself - hooks are quite picky when multiple react instances are present - see https://github.com/facebook/react/issues/14257. Tried doing the recommendations from there; Linked the package react using yarn link and added "react": "link:../node_modules/react" to package.json. Did not work for me.

The solution which worked for me:

  • remove package.json/tsconfig.json from example
  • install parcel as dev dependency in the package root.
  • re-point the import in example/index.tsx to 'src/index.tsx`.
  • start the example from the root with parcel example/index.html

Probably not perfect, but at least it works quite fast.