Search code examples
javascriptreactjsreduxredux-saga

Redux keeps re-rendering when state doesn't change


I'm making my first React-Redux project.

I learned React re-render when only be triggered if a component's state has chanaged.

But I'm so confused now.

Because states are not changed but component is re-rerendered every 1 to 3 secs. Fully matched data

I tried shallowEqual, but it didn't work.

Why is this happening?

// container
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';

import Home from 'presentations/Home';
import * as homeActions from 'modules/home';

const HomeContainer = () => {
    const dispatch = useDispatch();
    const list = useSelector(state => state.home.list);

    dispatch(homeActions.getList());

    console.log(list);

    return (
        <Home
        />
    );
}

export default HomeContainer;
// Redux module
import axios from 'axios';
import { call, put, takeEvery } from 'redux-saga/effects';
import { createAction, handleActions } from 'redux-actions';

function getListAPI() {
    return axios.get('http://localhost:8000/');
}

const GET_LIST         = 'home/GET_LIST';
const GET_LIST_SUCCESS = 'home/GET_LIST_SUCCESS';
const GET_LIST_FAILURE = 'home/GET_LIST_FAILURE';

export const getList = createAction(GET_LIST);

function* getListSaga() {
    try {
        const response = yield call(getListAPI);
        yield put({ type: GET_LIST_SUCCESS, payload: response });
    } catch (e) {
        yield put({ type: GET_LIST_FAILURE, payload: e });
    }
}

const initialState = {
    list: []
};

export function* homeSaga() {
    yield takeEvery('home/GET_LIST', getListSaga);
}

export default handleActions(
    {
        [GET_LIST_SUCCESS]: (state, action) => {
            const temp = action.payload.data;
            return {
                list: temp
            };
        }
    }, initialState
);

Solution

  • You are calling dispatch = useDispatch(); inside the functional component body which updates the state list which causes re-render and then your dispatch = useDispatch(); is executed and so on.

    Dispatch your action in useEffect to solve the issue

    const HomeContainer = () => {
      const dispatch = useDispatch();
      const list = useSelector((state) => state.home.list);
      useEffect(() => { //<---like this
        dispatch(homeActions.getList());
      }, []);
    
      console.log(list);
    
      return <Home />;
    };