DEV Community

Cover image for Show loading animation with custom hook in react
Ab. Karim
Ab. Karim

Posted on

Show loading animation with custom hook in react

This animation will work with a loading class in body. If the loading class exists on body animation will be shown, if not animation will removed.

In this way we can reduce our import export statement in every file we want to use loading.

We will start our loading animation with style.css file.

note I'm using tailwindcss

body.loading {
  overflow: hidden;
}

body.loading::before {
  content: '';
  background-color: rgba(0, 0, 0, 0.85);
  position: absolute;
  inset: 0;
  z-index: 100;
  @apply backdrop-blur-sm;
}

body.loading::after {
  content: '';
  position: absolute;
  background-image: url('./src/assets/img/load.png');
  background-repeat: no-repeat;
  background-position: center;
  background-size: max(3vw, 50px);
  z-index: 101;
  inset: 0;
  @apply animate-spin;
}

Enter fullscreen mode Exit fullscreen mode

First we removed overflow from body on loading to remove scrollbar, cause we don't wanna allow a user to scroll on page loading.

Then we added background black on loading(pseduo element before) class and filled it with window size and some more essestial style.

Then we added a Spin image, assign a top position with z-index and rotating with a animation.

Now create a hook to toggle loading class on body

create a file called useLoading.js

import { useEffect } from 'react';

export default function useLoading(state) {
  useEffect(() => {
    document.body.classList.toggle('loading', state);

    return () => document.body.classList.remove('loading');
  }, [state]);
}

Enter fullscreen mode Exit fullscreen mode

We had exported a function that receives bool to toggle class on body. If true passed class will be added, if false class will be removed.

In useEffect hook we can return a function to crean up our work on component unmount, in this case we are removing loading class from body. So, we don't need to worry about loading state on unmount anymore.

Let's use it

In any component you can use it.

// ... more import
import useLoading from "./useLoading";

export default function App() {
 const [loading, setLoading] = useState(true);
 useLoading(loading);

 useEffect(() => {
  // ... some heavy work
setLoading(false)
 }, [])

 //...

}

Enter fullscreen mode Exit fullscreen mode

We have a loading state we passed it to our useLoading hook. Now we can control our loading with just one line 😮. Yeah just update loading state 😀.

Github
Youtube in Bangla Language

Top comments (0)