Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda