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

In React, this error can happen for multiple reasons. In this post, we will try to cover some of the cases to generate the above issue.

React and react-dom version issue:

First of all, this issue can happen due to an outdated version of the react and react-dom library.

Improper hook call:

Following is an example of calling the useState hook from outside of the component function. See the code segment below:

const [data, setData] = useState(10);

function App() {

    return (
        <div className="App">
            <header className="App-header">
                <img src={logo} className="App-logo" alt="logo" />
                <h1 className="App-title">App Title</h1>
            </header>
            <p className="App-intro">
                The state is now: {data}
            </p>
            <button>Submit</button>
        </div>
    );
}

export default App;