In this short article I'll highlight why Cannot update a component from inside the function body of a different component warning happened in my specific case and how I fixed it.
The warning is being thrown at GamePageContainer
. This component runs a lot of hooks and contains minimal JSX because rendering happens in children. To be able to find the source of warning, I had to disable one hook at a time and re-render the page.
Finally I narrowed down the place of error to this hook:
export const useDispatchPlaying = (playing) => useDispatch()(playingAction(playing));
Because this is called directly in the calling component, as a hook, I noticed that action dispatched here is not wrapped in an effect.
So to get rid of the warning and make React happy, I refactored hook as follows:
export const useDispatchPlaying = (playing) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(playingAction(playing));
}, [playing]);
};
We can see here how indirect a warning message can be and it often requires a systematic approach to eliminate false-positives and carefully read through seamingly valid functions.