'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

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!



Solution 1:[1]

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>
  );
}

Solution 2:[2]

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.

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
Solution 2 LODASHRELOAD