Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!