I'm trying to refactor React.useReducer
to redux
(Redux Toolkit precisely).
I have a parent -> child wrapper component. I'm getting an error as below while calling dispatch()
:
Cannot update a component (`Child`) while rendering a different component (`Parent`)
In both Parent and Child I use selector. The code in short looks like that:
export const Child: React.FC<Props> = () => {
const state = useSelector((state: RootState) => state.slice);
const doAction = () => {
dispatch(update());
}
return (<div></div>)
}
export const Parent: React.FC<Props> = () => {
const state = useSelector((state: RootState) => state.slice); // <-- problem
doSomethingWithState(state);
return (<div></div>)
}
The fix I found is to import store like that:
import { store } from 'redux/store';
export const Parent: React.FC<Props> = () => {
const state = store.getState();
doSomethingWithState(state);
return (<div></div>)
}
I've read here that relying on the store being a singleton exported from some module is not recommended way. Is there a more proper way to get the actual state from redux and don't get the error as above?