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...