I have implemented my custom hook "useReducerWithCallback"
export default function useReducerWithCallback(
reducer,
initialState,
initializer
) {
const [state, dispatch] = useReducer(reducer, initialState, initializer);
const callbackRef = useRef(undefined);
const customDispatch = (action, callback) => {
callbackRef.current = callback;
console.log("Callback updated"); // <-------
dispatch(action);
};
useEffect(() => {
console.log("Executing callback"); // <--------
callbackRef.current?.(state);
}, [state]);
return [state, customDispatch];
}
which basically works like the typical useStateWithCallback but with a useReducer.
I am using this hook in a Context Provider, which is consumed in a screen that is inside a stack navigator.
This screen has a listener to my db, and when it is triggered, the screen communicates with my context provider reducer, passing a custom callback.
The problem I am having is when I push an other instance of the same screen in my stack navigator, as both screen listen to the same part of the DB, they communicate with the context provider at the same time, and their callbacks are overlapped.
This is my context provider:
function contentsReducer(contents, action) {
...
}
export function ContentsProvider({ children }) {
const [contents, dispatch] = useReducerWithCallback(
contentsReducer,
new Map([])
);
...
const addContents = (contents, callback = undefined) => {
console.log("Adding contents"); <------
dispatch(
{
type: "add-contents",
contents,
},
callback
);
};
...
}
The stack screen 1 and 2 (the last pushed one) are the same. Both communicate with the context provider using its method "addContents", which you see in the previous code, but for some reason, the callbacks are overlapped.
This is the result of the useReducerWithCallback:
Adding contents
Callback updated
Adding contents
Callback updated
Executing callback
Executing callback
When it should be:
Adding contents
Callback updated
Executing callback
Adding contents
Callback updated
Executing callback
Any ideas? I think that the problem is because of the centralization of the reducer in one unique point, the context provider, but I don't know how to fix this.
Thank you.