L12
L12

Reputation: 85

React re-renders even with no change

We have set up a project with redux. In this project, we get an info objecat from an api and insert it into the store. Now we noticed that the function components re-render even if the api return the same state as in the previous request.

We think it's because we are overwriting the store but we are not sure.

ChatContainer.js

const mapStateToProps = function (state) {
  return {
    content: state.info.content,
    loading: state.info.loading,
  }
}

const ChatContainer = connect(
  mapStateToProps,
)(Chat)
export default ChatContainer

Chat.js

function Chat(props) {

    const { content, loading } = props;
    return (
        <Info content={content} loading={loading} />
    ) 
}

action.js


export function setInfo(info) {
  return {
    type: SET_INFO, info: {
      content: info,
      loading: false
    }
  }
}

reducer.js

function setInfo(state = { content: [], loading: true }, action) {
  switch (action.type) {
    case SET_INFO:
      return action.info
    default:
      return state
  }
}

const appReducer = combineReducers({
...
  info: setInfo,
...
})
export default appReducer

Upvotes: 0

Views: 145

Answers (1)

Kaca992
Kaca992

Reputation: 2265

If state.info.content is an object, every time you change it with setInfo it will have a new reference. React-redux does a shallow compare on the result of mapStateToProps, so if your content is a different reference every time your component will re-render. connect HOC has an options parameter that you can use to implement a custom compare.

My advice would be to add a check to your setInfo or to the code calling setInfo and not calling your API if data is already loaded/didn't change(don't know your business logic).

Upvotes: 1

Related Questions