Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hook "useState" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function

Tags:

reactjs

React Hook is not working, giving error as attached screenshot:- enter image description here

My Code:-

import React, { useState} from 'react';

import WEBINAR_LIST from './webinar_data';

const [ page, setPage ] = useState(0); //create page state

const pageData = useMemo(() => {

     return WEBINAR_LIST.slice(page*5, (page*5)+5)
},[page])

const nextPage = () => setPage(prev => prev+1)
const prevPage = () => setPage(prev => prev > 0 ? prev-1 : prev) 

Thanks!

like image 951
Rohit Verma Avatar asked Jun 14 '26 13:06

Rohit Verma


2 Answers

You can't call React Hooks at top level, you will need to create a functional component.

Learn more about compontents here and about hooks here.

A functional component looks something like this:

import React, { useState } from 'react';

// Create your functional component:
function Example() {
  // And now you can use hooks
  // But only inside your functional component's
  // body
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
like image 65
Andrej Avatar answered Jun 17 '26 02:06

Andrej


In other words you most likely need to move your const below your main function. For me i had to move my const with useState below export function App.

like image 36
LODASHRELOAD Avatar answered Jun 17 '26 04:06

LODASHRELOAD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!