Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Throttle/debounce spinner (loading message) - not show if request is faster than X milliseconds

I'm preparing spinners in my react app.

It works great. However, some UX tips say, that spinner/loader/etc should be displayed after some waiting time. For this example, let's say it should be 750ms.

How can I throttle/debounce (I'm still not sure what is the difference) re-render component?

Edit xlxk611rzw

In above example, loading state should not be appear anytime.

like image 923
Mateusz Jagiełło Avatar asked Jul 30 '18 21:07

Mateusz Jagiełło


1 Answers

With Hooks and effects:

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

const DelayedSpinner = ({ size }) => {
  const [showSpinner, setShowSpinner] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => setShowSpinner(true), 750);

    return () => clearTimeout(timer);
  });

  return showSpinner && <Spinner size={size} color="primary" />;
};

export default DelayedSpinner;
like image 152
Shota Avatar answered Sep 22 '22 22:09

Shota