I am using redux-toolkit in my react application. I use useSelector & useDispatch in the react components to manage the states the component controls. Outside the react component, I also call the dispatch function in js code (meaning outside react component) to update the state.
The issue I am facing is that inside this function I run multiple dispatches at once. This results in the useSelector for my component updating on every dispatch. How can I batch all of these dispatches so that useSelector only re-renders the react component once?
Here is an example of my code. Let's say the react component "counter" has the following:
const count = useSelector(state => state.count)
const title = useSelector(state => state.title)
const name = useSelector(state => state.name)
Now lets say outside my react component I have a global window function that calls multiple functions:
window.foo = () => {
function1();
function2();
function3();
}
Now lets say each of function1(), function2(), function3() call the redux dispatch function to update the state's title, name, and count.
Currently my component will re-render 3 times for each useSelector I used. I want useSelector to only re-render once when all 3 dispatches have already been called.
I am aware of the react-redux batch function, but I was looking for another solution because I don't want to force myself to only call dispatch in one function. Is there a way to delay the default "waiting" period that redux waits before executing all the dispatches in its queue that I can increase?
P.S. I'm assuming there has to be some kind of "waiting period" because redux dev tools extension implied of such. Plus from personal testing I noticed that if you call dispatch() twice back to back, use selector will only be called once, thus that leads me to believe there must be some kind of waiting period for redux.