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

107
Visualizações
Whats making my mouseover and react setState slow?

It feels like any sort of "click and drag" type of action I create feel kind of... well choppy. Like it's stuttering. I know when I console log the data is instant from the event, but the delays within the update to state are what makes it seem slower.

Here is a very simple example:

const TestMouseOver = () => {
  const [pos, setPos] = useState();

  const onMouseDown = (e) => {
    setPos({
      x: e.clientX + document.body.scrollLeft,
      y: e.clientY + document.body.scrollTop,
    })
  }
  const onMouseMove = (e) => {
    setPos({
      x: e.clientX + document.body.scrollLeft,
      y: e.clientY + document.body.scrollTop,
    })
  }
  return (
    <div
      onMouseDown={(event) => onMouseDown(event)}
      onMouseMove={(event) => onMouseMove(event)}
      onMouseUp={() => setPos(null)}
    >
      {pos && <MoveBox position={pos} />}
    </div>
  );
};

within MoveBox I take the pos and just set the div's absolute css as the position (styled-components). Nothing to fancy in there. It works but it's laggy and slow.

Should I be attempted to build some sort of lerp or animation to go to last know cord to smooth out the position update?

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

0

MouseEvents are not throttled : everytime your mouse move, it will call your setState functions. That can happen hundreds of time a second, causing React to rerender as often which is by far suboptimal.

At max tempo, React shouldn't rerender more than every frame of 16ms to ensure smooth 60 FPS animations on your website.

You need to throttle these events by using lodash.throttle for example and register a callback using useCallback.

Sample code :

const handleMouseMove = useCallback(lodash.throttle((e) => {
    setPos({
      x: e.clientX + document.body.scrollLeft,
      y: e.clientY + document.body.scrollTop,
    });
}, 16), []);

return (
    <div onMouseMove={handleMouseMove}>{...}</div>
)

Notice the 16 as the second argument of lodash.throttle : it ensures the function doesn't get called more often than every 16ms.

about 4 years ago · Juan Pablo Isaza Relatório

0

Another possible approach you should consider would be to use a browser native api requestAnimationFrame

https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

This is how it would be implemented for your specific case

const TestMouseOver = () => {
  const [pos, setPos] = useState();
  let ticking = false;

  function onMouseMove(event) {
    requestTick(event);
  }

  function onMouseDown(event) {
    requestTick(event);
  }

  function requestTick(event) {
    if (!ticking) {
      requestAnimationFrame(update(event));
    }
    ticking = true;
  }

  function update(e) {
    // reset the tick so we can capture next mouseevent
    ticking = false;

    setPos((prevState) => ({
      x: e.clientX + document.body.scrollLeft,
      y: e.clientY + document.body.scrollTop,
    }))
  }

  return (
    <div
      onMouseDown={(event) => onMouseDown(event)}
      onMouseMove={(event) => onMouseMove(event)}
      onMouseUp={() => setPos(null)}
    >
      {pos && <MoveBox position={pos} />}
    </div>
  );
};

PROS:

  • No need of any external libraries
  • Executes on a frame basis. So, UI behaviour is smooth.

CONS:

  • Does not have IE9 support
  • Cannot define throttle duration because it is coupled to framerate

How it works: Basically, using a variable and requestAnimationFrame method, we make sure that the state is updated at the rate of frame update

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