Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

236
Visualizações
Call react hooks inside event handler

I need to re-fetching data if i click some button, but when i call hook inside click handler i get following error

const Menus = ({ menus, title }) => {
  const handleClick = () => {
    const { data: cartItems } = useFetch(API_URL + 'cart');
  }
}

src\components\Menus.js | Line 26:13: React Hook "useFetch" is called in function "handleMenu" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter react-hooks/rules-of-hooks

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

React hooks can't be used inside a pure JavaScript function. It will break the rules of hooks. Hooks can only be used in React function components. A function returning ReactElement will be treated as a React function component instead of a normal function in JS.

You should return the data and a data fetch function in the useFetch hook. So that you can use the data fetch function later.

E.g.

import React from 'react';
import { useCallback, useEffect, useState } from 'react';

const API_URL = 'http://localhost:8080/api/';
const api = {
  async getCartItems() {
    return ['apple', 'banana'];
  },
};

function useFetch(url: string) {
  const [cartItems, setCartItems] = useState<string[]>([]);
  
  // fetch data later use this function.
  const getCartItems = useCallback(() => {
    return api.getCartItems().then((res) => {
      setCartItems(res);
    });
  }, [url]);
 
  // fetch data when component mount
  useEffect(() => {
    getCartItems();
  }, [url]);

  return { data: cartItems, getCartItems };
}

const Menus = () => {
  const { data: cartItems, getCartItems } = useFetch(API_URL + 'cart');
  const handleClick = () => {
    getCartItems();
  };

  return (
    <div onClick={handleClick}>
      <ul>
        {cartItems.map((item, i) => {
          return <li key={i}>{item}</li>;
        })}
      </ul>
    </div>
  );
};
about 4 years ago · Juan Pablo Isaza Relatório

0

As the error mentions, the issue violates the rules of hooks (react-hooks/rules-of-hooks) More information can be found here: https://reactjs.org/docs/hooks-rules.html

You can only use hooks in the top level of functional components but the handleClick() function would put the hook at the second level rather than the top level.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda