Skip to content Skip to sidebar Skip to footer

How To Fix React(TypeScrtipt) Error "Invalid Hook Call."?

I got error: 'Invalid hook call. Hooks can only be called inside of the body of a function component.' in react function: interface Items { items: any[] } const [items, setItems

Solution 1:

You need to call React Hooks from within a component, like so:

interface Items {
  items: any[]
}

const ItemsList: React.FC<Items> = ({ items }) => {
  const [items, setItems] = useState<Items>();
 
  useEffect(() => {
    const response = Http.get<Items>(url).then(res => setItems(res)) || [] as Items[]
  }, []);

  return (
      <ul>
        {items.map((item) => {
          return (
            <ItemPreview key={item.id} item={item}/>
          );
        })}
      </ul>
  )
}

export default ItemsList

See the Rules of Hooks for more information:

Only Call Hooks from React Functions

Don’t call Hooks from regular JavaScript functions. Instead, you can:

  • ✅ Call Hooks from React function components.
  • ✅ Call Hooks from custom Hooks.

Post a Comment for "How To Fix React(TypeScrtipt) Error "Invalid Hook Call."?"