0

The React warning "Cannot update a component while rendering a different component" was added to ver 16.13.0 of React. The cause of the warning can be somewhat difficult to trace.

The React blog states:

A React component should not cause side effects in other components during rendering. It is supported to call setState during render, but only for the same component.

The question is, can Redux cause this behavior?

1 Answer 1

1

Yes, if you make a mistake. I wrote a Redux thunk action (an async action) that sometimes would find the needed data in cache right away and dispatch an action event during that render. Sometimes this action would update state that was used on many pages. This caused the warning.

A part of the state

import {createSlice} from '@reduxjs/toolkit';

export const dataSlice = createSlice({
    name: 'data',
    initialState: {
        /** Base data from server */
        baseData: null,

        // === Place page ===

        /** Fetching status for place data */
        placeDataFetchStatus: FetchStatus.NOT_STARTED,
        ...

Here I'm fetching data for the component PlacePage during its render

function PlacePage(props) {
    const dispatch = useDispatch();
    const {place_uri, area_uri, place_type_uri} = useParams();

    dispatch(fetchPlacePageData(place_uri, area_uri, place_type_uri));

This async action caused the warning

export const fetchPlacePageData = (place_uri, area_uri, place_type_uri) => (dispatch, getState) => {
    DataFetcher.implFetchPlacePageData(dispatch, getState, place_uri, area_uri, place_type_uri);
};


export const implFetchPlacePageData = (dispatch, getState, reqPlaceInfo, place_uri, area_uri, place_type_uri) => {
    ...

    // check if data is in cache
    const data = PlacePageDataCache.getData(id);
    if (data) {
        # The base data is used on many pages, this dispatch causes the warning 
        dispatch(set_base_data(data.base_data));

        dispatch(set_all_place_data(data.place_data));
        return;
    }

This is the stack trace from the browser console log:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for providing such a detailed answer to your question. This will be helpful to others with similar problems!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.