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

116
Vistas
Dispatch and Listen Action with Hooks in React (without Redux)

I wanted to share actions through different places in the component tree like:

// in one component, listen an action
useListener("DELETE", (payload) => {
    console.log("DELETE EVENT 1", payload);
});

// in another component, dispatch action
const dispatch = useDispatch();
dispatch("DELETE", payload);

I come up with such implementation :

const globalListener = {};

export const useListener = (actionName = "default", fn, dependencies = []) => {
    const listenerRef = useRef(Symbol("listener"));

    useEffect(() => {
        const listener = listenerRef.current;
        return () => {
            delete globalListener[actionName][listener];
        };
    }, []);

    useEffect(() => {
        const listener = listenerRef.current;
        if (!globalListener?.[actionName]) {
            globalListener[actionName] = {};
        }
        globalListener[actionName][listener] = fn;
    }, dependencies);
};

export const useAction = () => {
    const dispatch = (actionName, payload) => {
        const actionListener = globalListener?.[actionName];
        if (!actionListener) {
            return;
        }

        const keys = Reflect.ownKeys(actionListener);
        keys.forEach((key) => {
            actionListener[key]?.(payload);
        });
    };
    return dispatch;
};

I would like to hear what kind of risks/flaws can such implementation bring. I think I could use useReducer's middleware for such usage but it would be overkill to use the whole useReducer code to do such implementation.

Also; what could be other approaches to solve this? With or without any extra library...

about 4 years ago · Juan Pablo Isaza
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