1

I'm trying to upgrade to React 17 and use the new JSX Transform to avoid import React from 'react'. When I remove import React from a component, the page crashes with an error (only when rendering that component).

React is not defined

I thought I could solve this by changing my webpack config:

// module > rules > use > options > presets
{
  presets: [
    ['@babel/preset-react', { runtime: 'automatic' }]
  ]
}

(It had previously only been '@babel/preset-react' without the options.)

After compiling, I am presented with several errors in the console:

Warning: Cannot update a component while rendering a different component.

Warning: Can't perform a React state update on an unmounted component.

Warning: Cannot update during an existing state transition (such as within 'render').

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

The app loads more or less okay until it gets to the React-Table, and then won't go any further after the invalid hook call error.

I've updated some packages to ensure they should be on the correct version:

{
  "@babel/core": "7.16.0",
  "@babel/preset-env": "7.16.4",
  "@babel/preset-react": "7.16.0",
  "babel-loader": "8.2.3",
}

Any idea why adding { runtime: 'automatic' } messes up how React is operating?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
HaveSpacesuit
  • 3,572
  • 6
  • 40
  • 59
  • Is the `React` import used for anything other than `createElement` (e.g. `React.useState` - _"we would still need to import React in order to use Hooks or other exports that React provides"_)? Give a [mre]. – jonrsharpe Nov 30 '21 at 16:41
  • 1
    Yes, I also have `import { useState, etc } from 'react'`, but I see this error even if I restore `import React`. Basically, the only change I make is to add `{ runtime: 'automatic' }`, and everything 'splodes. – HaveSpacesuit Nov 30 '21 at 16:45

1 Answers1

0

I had faced similar issues while trying to adopt JSX Transform. I would point out two issues you might be having here.

  1. Once you upgrade your React version to 17/ 16.14.x you need to do a npm/yarn clean and reinstall all your dependencies and restart the server. And you have to do this everytime you switch between React <16.x and React 17 branches.
  2. The Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component that you're getting is not related to any of your changes. Maybe you've mistakenly called a hook outside of a functional component,you can check your code for that.Once this is fixed, JSX Transform will work as smooth as butter!!