React Hooks Error: Hooks can only be called inside the body of a function component

后端 未结 17 2072
旧巷少年郎
旧巷少年郎 2020-12-05 04:07

I am getting this error when using the useState hook. I have this in it\'s basic form, looking at the react docs for a reference, but am still getting this erro

相关标签:
17条回答
  • 2020-12-05 04:16

    I had a problem in a monorepo, where a package docz used react@16.6.3 and the final output bundle had two react versions.

    Issue on Github

    Fixed it by removing the package

    0 讨论(0)
  • 2020-12-05 04:19

    My issue was the following:

    I was doing: ReactDOM.render(Example(), app);

    Whereas I should have been doing: ReactDOM.render(<Example />, app);

    0 讨论(0)
  • 2020-12-05 04:21

    Just to elaborate on @rista404's answer, including duplicate versions of react (and perhaps react-dom) will yield the same error depending on where you are using your hooks. Here are two examples...

    1. An external dependency includes another version of react in its dependencies, likely by mistake as react should usually be a peer dependency. If npm doesn't automatically dedupe this version with your local version, you may see this error. This is what @rista404 was referring to.
    2. You npm link a package that includes react in its devDependencies or dependencies. Now, for modules in this package, you may see errors if they pull a different version of react from the their local node_modules directory rather than the parent project's.

    The latter can be fixed when bundling with webpack by using resolve.alias like so...

        resolve: {
            alias: {
                'react': path.resolve(__dirname, 'node_modules/react'),
                'react-dom': path.resolve(__dirname, 'node_modules/react-dom')
            }
        }
    

    This will ensure react is always pulled from the parent project's node_modules directory.

    0 讨论(0)
  • 2020-12-05 04:24

    I experienced this error while using Parcel's Hot Module Replacement, and fixed by updating react-dom to it's alpha version:

    yarn add react-dom@16.7.0-alpha.0
    

    See this issue.

    0 讨论(0)
  • 2020-12-05 04:24

    The problem for me was indeed react-hot-loader.

    You can disable react-hot-loader for a single component instead of the entire app using the cold method like this:

    import { cold } from 'react-hot-loader'
    
    export const YourComponent = cold(() => {
    
      // ... hook code
    
      return (
        // ...
      )
    })
    

    OR

    export default cold(YourComponent)
    
    0 讨论(0)
  • 2020-12-05 04:25

    found this workaround for react-hot-loader while that PR to fix it is inbound.

    Wrap the function that calls hooks in a React.memo, preventing a hot reload if it's unchanged.

    const MyFunc = React.memo(({props}) => {...

    Credit for solution: https://github.com/gatsbyjs/gatsby/issues/9489

    0 讨论(0)
提交回复
热议问题