Rohit Verma
Rohit Verma

Reputation: 3785

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!

Upvotes: 8

Views: 44262

Answers (3)

Muhammad Bilawal
Muhammad Bilawal

Reputation: 474

You can use the useState hook like this at top level

import { useState } from "react"

const [ page, setPage ] = useState(0) // it should not be initilize here

export default function Example() {
  return (
    <div>Example</div>
  )
}

You should use it like below example

import { useState } from "react"

export default function Example() {
  
    const [ page, setPage ] = useState(0) //use state should be inside function
  
    return (
    <div>Example</div>
  )
}

Upvotes: 0

LODASHRELOAD
LODASHRELOAD

Reputation: 31

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.

Upvotes: 3

Andrej
Andrej

Reputation: 3225

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

Upvotes: 11

Related Questions