Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda