Search code examples
javascriptreactjsreselect

Reselect always re rendering


I'm trying to add reselect to my react code but it seems to be always rerendering.

Everytime I change my state the console prints "testing" even though the input-selector is not changing. I created a simple test to show you guys whats happening.

import { connect } from 'react-redux'
import { createSelector } from 'reselect'

window.testObject = {'x': '5'}
const mapStateToProps = (state, props) => {

  const test = state => {return window.testObject}
  const getTest = createSelector(test, (t)=> console.log('testing'))

  return {
      test: getTest(state),
  }
}


export default const TestContainer = connect(
  mapStateToProps,
)(TestBase)

What am I doing wrong?? I keep re reading the documentation and from what I can tell the console.log should not be running after the first time since the input-selector is not changing. Am I understanding that correctly?


Solution

  • You're calling the createSelector every time it re-renders

    move the createSelector outside of the mapStateToProps

    const getTest = createSelector(...)
    
    const mapStateToProps = (state, props) => ({
      test: getTest(state),
    })
    
    export default const TestContainer = connect(
      mapStateToProps,
    )(TestBase)