Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

259
Vistas
ReactJS Async - Using React Context to simulate a Singleton?

I currently have a hook:

function useFollowUser() {
    const isFollowing = useRef(false);

    return (userId) => {
       if(isFollowing.current) return; // mutual exclusion

       isFollowing.current = true;

       ... update DB and GUI

       isFollowing.current = false;
    }
}

Then, I use it in my FollowButton component

function FollowButton({ userId }) {
   ...
   
   const followUser = useFollowUser();

   const handleOnPress = () => followUser(userId);
  
   return <Button onPress={handleOnPress} text=... />
}

The problem is that, if in the same screen I have two instances of the same component, with the same userId prop, there will be some data inconsistencies, as the followUser method, if the user press both buttons at the same time, might run in parallel.

In order to resolve this async issue, is a good option to move the hook logic to a Context provider?

Any other approach?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You could use context but simpler way is just to wrap isFollowing into same scope with self executing functions. Pay attention to two brackets that immediately invoke the function.

 const useFollowUser = (() => {
      let isFollowing = false;
    
      return () => {
     // this is hook context, you can use any effects here

        return (userId) => {
          if (isFollowing) return; // mutual exclusion
    
          isFollowing = true;
    
          // ... update DB and GUI
    
          isFollowing = false;
        };
      }
    })();

Usage:

const followUser = useFollowUser();
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda