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

135
Visualizações
useCallback returns n+1 times where n is the number of state variables

I'm trying to set up a custom context menu, however whenever the user right clicks the context menu function returns 6 separate times, the 5th being what I need and the 6th being the default state values. However if the user double right-clicks in the same spot it returns 5 times, with the 5th return being the desired values and the menu opens. Is there a way to check before the return if all the states are changed and only return from the callback if all the needed information is present?

const ContextMenu = outerRef => {
  const [xPos, setXPos] = useState("0px");
  const [yPos, setYPos] = useState("0px");
  const [menu, showMenu] = useState(false);
  const [menuTarget, setMenuTarget] = useState('');
  const [menuTargetId, setMenuTargetId] = useState('');
  const handleContextMenu = useCallback(
    event => {
      if(event.target.className && (event.target.className.includes('bar') ||event.target.className == 'timeline' || event.target.className == 'draggablediv' || event.target.className == 'editableDiv')){
         event.preventDefault();
         if (outerRef && outerRef.current.contains(event.target)) {
            setXPos(`${event.pageX}px`);
            setYPos(`${event.pageY}px`);
            setMenuTarget(event.target.className)
            setMenuTargetId(event.target.id)
            showMenu(true);

         } else {
             showMenu(false);
           }
       }
    },[showMenu, outerRef, setXPos, setYPos]);

const handleClick = useCallback(() => {
  showMenu(false);
}, [showMenu]);

useEffect(() => {
  document.addEventListener("click", handleClick);
  document.addEventListener("contextmenu", handleContextMenu);
  return () => {
    document.removeEventListener("click", handleClick);
    document.removeEventListener("contextmenu", handleContextMenu);
  };
}, []);

return {xPos, yPos, menu, menuTarget, menuTargetId};
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

useCallback accepts a function that returns the memoized value. Like useCallback(() => 5, []), or in your case useCallback(() => event => {...}, []).

This is because React has to call the function to get the value to memoize, so your setters are being called on every render. Which is what's causing all the weirdness.

However, even with that fix I don't think it's correct to use a function that changes references in addEventListener. You will never have up-to-date values in your contextmenu handler because it will refer to an old version of handleContextMenu. You will probably have to use a more idiomatic way of attaching a function to a UI event than the global document api.

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