'Updating JSX transform breaks React

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?



Solution 1:[1]

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!!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Swayam Mohanty