Uma saga épica sobre um pequeno gancho personalizado para React (geradores, sagas, rxjs)

parte 2. Geradores





Prelúdio

A tarefa era implementar um pré-carregador com uma contagem regressiva na reatância. Porque Não sei como pesquisar no Google e adoro esculpir bicicletas (uma boa bicicleta de dois lugares acabou sendo de duas bicicletas "Ucrânia"), então eu estava condenado a me aprofundar nos campos do assincronismo. Vou adiantar e dizer que implementei este pré-carregador usando geradores, redux-saga, rxjs. É uma experiência muito interessante e gostaria de compartilhá-la, visto que no decorrer do processo, além de artigos descrevendo o óbvio e fragmentos de informações puramente específicas sobre stackoverflow, não encontrei.





Então: parte um - criando um gancho personalizado.





Estrutura do pré-carregador

Quanto à escala do indicador de carregamento, escolhi a quantidade de fotos no site (você também pode selecionar outros recursos), pois no meu caso, esses eram os recursos mais pesados ​​da página.





Porque Tive que fazer isso na reação, então é claro que o projetei na forma de um gancho personalizado e denominei usePreloader.





O próprio código do pré-carregador
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>
  );
}

      
      







Estilos de pré-carregador
.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);
  }
}

      
      







Implementação de gancho

A lógica do gancho é pesquisar todas as tags <img> na página e anexar manipuladores para os eventos de carregamento e erro. Isso é feito usando o seguinte código





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;
};
      
      



O gancho terá um estado, que armazenará a etapa do indicador e o estado atual do indicador. Nesta (primeira) parte, o pré-carregador é implementado usando apenas os ganchos react, mas em várias versões. Não vamos conectar redux para armazenar o estado, porque este é um gancho personalizado e gostaria de reutilizá-lo no futuro.





Código fonte Js
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,
};

      
      







Opção 1 (não funciona, para maior clareza). 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





  • diferença no comportamento do componente ao usar os ganchos useEffect e useLayoutEffect









Link da sandbox





Link do repositório





Isso pode ser o fim, porque o gancho funciona. Mas esse pré-carregador inesperadamente acabou sendo um ótimo exemplo para trabalhar com o fluxo de eventos e seu processamento assíncrono. Portanto, a diversão começa na próxima parte.





Vamos começar, ou melhor, continuar com os geradores ...
















All Articles