Invalid hook call. Hooks can only be called inside of the body of a function component. when I use useState in my react project

I use electron-react-boilerplate as my demo project:

I get error:
enter image description here

Error
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

I checked the version and instances count of react as below:

$ pnpm ls react-dom 
Legend: production dependency, optional only, dev only

/Users/john/demo

dependencies:
react-dom 18.2.0

$ pnpm ls react
Legend: production dependency, optional only, dev only

/Users/jonh/demo

dependencies:
react 18.2.0

and my code as below:

import React, { useEffect, useState } from 'react'

import { pagesKey } from '../../1.config/pages.config'

import { Card } from 'antd';

function index() {
  const [aaa, setAaa] = useState('123')
  console.log(aaa)

//  useEffect(() => {

//  }, [])

  console.log(window.React)

  return (
    <div style={{padding: '16px'}}>

      <Card title="Card title" size="small" bordered={true} style={{ width: 300 }}>
        <p>Card content</p>
        <p>Card content</p>
        <p>Card content</p>
      </Card>
    </div>
  )
}

export default index

I don’t see anything wrong in my code, but why it get this error?


Edit-01

I tried name function using PascalCase as below, but still get this error:

function Index() {
  ...
}

export default Index

this is my file path:

/src/renderer/pages/localMachineTools/localMachineHardware/cpu.tsx

enter image description here

  • can you share the filename that your using to save this index component

    – 

  • @AnanduReghu Updated my post, please check it.

    – 

  • Your stack trace includes an onClick callback, but the code you posted here does not. Can you include the rest of the Index component?

    – 

Function components that return valid JSX should be named using PascalCase. Like this:

function Index() {
  ...
}

export default Index;

or

const Index = () => {
  ...
}

export default Index;

Check the official React docs for more info.

Leave a Comment