Prelude
The task was to implement a preloader with a countdown on the reactance. Because I donβt know how to google and I love to sculpt bicycles (a good two-seater turned out to be from two bicycles "Ukraine"), then I was doomed to dig deeply in the fields of asynchronism. I'll run ahead and say that I implemented this preloader using generators, redux-saga, rxjs. It is a very interesting experience and I would like to share it, given that in the course of the proceedings, apart from articles describing the obvious things, and scraps of purely specific information on stackoverflow, I did not find.
So: part one - creating a custom hook.
Preloader structure
As the scale of the loading indicator, I chose the number of pictures on the site (you can also select other resources), because in my case, these were the heaviest resources on the page.
Because I had to do this in the react, then of course I designed it in the form of a custom hook and named it usePreloader.
Preloader code itself
import React from "react";
export default function Preloader() {
return (
<div className="preloader__wrapper">
<div className="preloader">
<svg
width="300"
height="300"
viewBox="0 0 300 300"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M300 150C300 232.843 232.843 300 150 300C67.1573 300 0 232.843 0 150C0 67.1573 67.1573 0 150 0C232.843 0 300 67.1573 300 150ZM20.7679 150C20.7679 221.373 78.6271 279.232 150 279.232C221.373 279.232 279.232 221.373 279.232 150C279.232 78.6271 221.373 20.7679 150 20.7679C78.6271 20.7679 20.7679 78.6271 20.7679 150Z"
fill="#F3F3F3"
/>
<path
d="M289.616 150C295.351 150 300.037 154.655 299.641 160.376C297.837 186.392 289.275 211.553 274.72 233.336C258.238 258.003 234.811 277.229 207.403 288.582C179.994 299.935 149.834 302.906 120.736 297.118C91.6393 291.33 64.9119 277.044 43.934 256.066C22.9561 235.088 8.66999 208.361 2.88221 179.264C-2.90558 150.166 0.0649254 120.006 11.4181 92.5975C22.7712 65.1886 41.9971 41.7618 66.6645 25.2796C88.4468 10.725 113.608 2.16293 139.624 0.359232C145.345 -0.0374269 150 4.64906 150 10.384C150 16.1189 145.343 20.7246 139.627 21.1849C117.723 22.9486 96.5686 30.2756 78.2025 42.5475C56.9504 56.7477 40.3864 76.931 30.6052 100.545C20.8239 124.159 18.2647 150.143 23.2511 175.212C28.2375 200.28 40.5457 223.307 58.6191 241.381C76.6926 259.454 99.7195 271.762 124.788 276.749C149.857 281.735 175.841 279.176 199.455 269.395C223.069 259.614 243.252 243.05 257.453 221.797C269.724 203.431 277.051 182.277 278.815 160.373C279.275 154.657 283.881 150 289.616 150Z"
fill="#6CAE30"
/>
</svg>
</div>
<div className="preloader__counter">0%</div>
</div>
);
}
Preloader styles
.App {
font-family: sans-serif;
text-align: center;
}
.preloader__wrapper {
position: fixed;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #ffffff;
z-index: 2000;
}
.preloader {
position: relative;
width: 18.75rem;
height: 18.75rem;
}
.preloader svg {
width: 18.75rem;
height: 18.75rem;
-webkit-animation: spin 4s infinite linear;
animation: spin 4s infinite linear;
}
.preloader__counter {
margin-top: 1.625rem;
padding-left: 1rem;
font-family: sans-serif;
font-size: 3.125rem;
line-height: 1;
color: #6cae30;
}
@media (max-width: 900px) {
.preloader {
width: 6.25rem;
height: 6.25rem;
}
.preloader svg {
width: 6.25rem;
height: 6.25rem;
}
.preloader__counter {
margin-top: 0.75rem;
padding-left: 0.5rem;
font-size: 2.125rem;
}
}
@-moz-keyframes spin {
from {
-moz-transform: rotate(0deg);
}
to {
-moz-transform: rotate(360deg);
}
}
@-webkit-keyframes spin {
from {
-webkit-transform: rotate(0deg);
}
to {
-webkit-transform: rotate(360deg);
}
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
Hook implementation
The hook logic is to find all <img> tags on the page and attach handlers for the load and error events. This is done using the following code
const updateCounter = () => {
dispatch({
type: ACTIONS.SET_COUNTER,
data: state.counter + state.counterStep
});
};
const checkImageLoading = (url) => {
const imageChecker = new Image();
imageChecker.addEventListener("load", updateCounter);
imageChecker.addEventListener("error", updateCounter);
imageChecker.src = url;
};
The hook will have a state, which will store the indicator step and the current indicator state. In this (first) part, the preloader is implemented only using the react hooks, but in several versions. We will not connect redux to store the state, because this is a custom hook and would like to reuse it in the future.
Js source code
export const SET_COUNTER = "SET_COUNTER";
export const SET_COUNTER_STEP = "SET_COUNTER_STEP";
export const initialState = {
counter: 0,
counterStep: 0,
};
export const reducer = (state, action) => {
switch (action.type) {
case SET_COUNTER:
return { ...state, counter: action.data };
case SET_COUNTER_STEP:
return { ...state, counterStep: action.data };
default:
throw new Error("This action is not applicable to this component.");
}
};
export const ACTIONS = {
SET_COUNTER,
SET_COUNTER_STEP,
};
Option 1 (not working, for clarity). useReducer
, , useRef . checkImageLoading state .
usePreloader.js
import { useReducer, useEffect } from "react";
import { reducer, initialState, ACTIONS } from "./state";
const PRELOADER_SELECTOR = ".preloader__wrapper";
const PRELOADER_COUNTER_SELECTOR = ".preloader__counter";
const usePreloader = () => {
const [state, dispatch] = useReducer(reducer, initialState);
const preloaderEl = document.querySelector(PRELOADER_SELECTOR);
const counterEl = document.querySelector(PRELOADER_COUNTER_SELECTOR);
const updateCounter = () => {
dispatch({
type: ACTIONS.SET_COUNTER,
data: state.counter + state.counterStep
});
};
const checkImageLoading = (url) => {
const imageChecker = new Image();
imageChecker.addEventListener("load", updateCounter);
imageChecker.addEventListener("error", updateCounter);
imageChecker.src = url;
};
useEffect(() => {
const imgArray = document.querySelectorAll("img");
if (imgArray.length > 0) {
dispatch({
type: ACTIONS.SET_COUNTER_STEP,
data: Math.floor(100 / imgArray.length) + 1
});
imgArray.forEach((img) => {
checkImageLoading(img.src);
});
}
}, []);
useEffect(() => {
if (counterEl) {
state.counter < 100
? (counterEl.innerHTML = `${state.counter}%`)
: hidePreloader(preloaderEl);
}
}, [state]);
return;
};
const hidePreloader = (preloaderEl) => {
preloaderEl.remove();
};
export default usePreloader;
2. useReducer + useRef
, useRef . state .
:
// state
const stateRef = useRef(state);
state current stateRef:
const updateCounter = () => {
dispatch({
type: ACTIONS.SET_COUNTER,
data: stateRef.current.counter + stateRef.current.counterStep // state, stateRef
});
};
state
stateRef.current.counter < 100
? (counterEl.innerHTML = `${stateRef.current.counter}%`) // state, stateRef
: hidePreloader(preloaderEl);
state, :
useEffect(() => {
stateRef.current = state; // state, state
...
}, [state]);
useReducer + useRef
import { useReducer, useEffect, useRef } from "react";
import { reducer, initialState, ACTIONS } from "./state";
const PRELOADER_SELECTOR = ".preloader__wrapper";
const PRELOADER_COUNTER_SELECTOR = ".preloader__counter";
const usePreloader = () => {
const [state, dispatch] = useReducer(reducer, initialState);
// state
const stateRef = useRef(state);
const preloaderEl = document.querySelector(PRELOADER_SELECTOR);
const counterEl = document.querySelector(PRELOADER_COUNTER_SELECTOR);
const updateCounter = () => {
dispatch({
type: ACTIONS.SET_COUNTER,
data: stateRef.current.counter + stateRef.current.counterStep // state, stateRef
});
};
const checkImageLoading = (url) => {
const imageChecker = new Image();
imageChecker.addEventListener("load", updateCounter);
imageChecker.addEventListener("error", updateCounter);
imageChecker.src = url;
};
useEffect(() => {
const imgArray = document.querySelectorAll("img");
if (imgArray.length > 0) {
dispatch({
type: ACTIONS.SET_COUNTER_STEP,
data: Math.floor(100 / imgArray.length) + 1
});
imgArray.forEach((img) => {
checkImageLoading(img.src);
});
}
}, []);
useEffect(() => {
stateRef.current = state; // state, state
if (counterEl) {
stateRef.current.counter < 100
? (counterEl.innerHTML = `${stateRef.current.counter}%`) // state, stateRef
: hidePreloader(preloaderEl);
}
}, [state]);
return;
};
const hidePreloader = (preloaderEl) => {
preloaderEl.remove();
};
export default usePreloader;
. ( network devtools), . , . ..
useEffect(() => {
...
}, [state]);
state. stateRef.current . .
, useEffect useLayoutEffect:
useLayoutEffect(() => {
stateRef.current = state;
if (counterEl) {
stateRef.current.counter < 100
? (counterEl.innerHTML = `${stateRef.current.counter}%`)
: hidePreloader(preloaderEl);
}
}, [state]);
.
useEffect - . .. - state .
useLayoutEffect - . .. .
: , , useLayoutEffect; , - useEffect.
3. useState + useRef
useReducer, .. : . useState. couterStep :
const [counterStep, setCounterStep] = useState(0);
const counterStepStateRef = useRef(counterStep);
const setCounterStepState = (data) => {
counterStepStateRef.current = data;
setCounterStep(data);
};
useState + useRef
import { useEffect, useLayoutEffect, useRef, useState } from "react";
const PRELOADER_SELECTOR = ".preloader__wrapper";
const PRELOADER_COUNTER_SELECTOR = ".preloader__counter";
const usePreloader = () => {
const [counter, setCounter] = useState(0);
const counterStateRef = useRef(counter);
const setCounterState = (data) => {
counterStateRef.current = data;
setCounter(data);
};
const [counterStep, setCounterStep] = useState(0);
const counterStepStateRef = useRef(counterStep);
const setCounterStepState = (data) => {
counterStepStateRef.current = data;
setCounterStep(data);
};
const preloaderEl = document.querySelector(PRELOADER_SELECTOR);
const counterEl = document.querySelector(PRELOADER_COUNTER_SELECTOR);
const updateCounter = () => {
setCounterState(counterStateRef.current + counterStepStateRef.current);
};
const checkImageLoading = (url) => {
const imageChecker = new Image();
imageChecker.addEventListener("load", updateCounter);
imageChecker.addEventListener("error", updateCounter);
imageChecker.src = url;
};
useEffect(() => {
const imgArray = document.querySelectorAll("img");
if (imgArray.length > 0) {
setCounterStepState(Math.floor(100 / imgArray.length) + 1);
imgArray.forEach((img) => {
checkImageLoading(img.src);
});
}
}, []);
useLayoutEffect(() => {
if (counterEl) {
counterStateRef.current < 100
? (counterEl.innerHTML = `${counterStateRef.current}%`)
: hidePreloader(preloaderEl);
}
}, [counter, counterStep]);
return;
};
const hidePreloader = (preloaderEl) => {
preloaderEl.remove();
};
export default usePreloader;
export default function App() {
usePreloader();
return (
<div className="App">
<Preloader />
...
</div>
);
}
:
:
useReducer useState
useRef
difference in component behavior when using useEffect and useLayoutEffect hooks
Sandbox link
Repository link
This could be the end, because the hook works. But this preloader unexpectedly turned out to be a great example for working with the flow of events and their asynchronous processing. Therefore, the fun begins in the next part.
Let's start, or rather continue, with generators ...