0
votes

I'm having a trouble implementing shouldComponentUpdate on my React app with loadingData state. I want to prevent component to load again when nextProps has not changed from the this.props which is working fine and it messes up loadingData value some how and I can't find the reason why.

Why loadingData ended up to be true even there's no change to the data in Redux(nextProps and this.props)?

  constructor(props){
    super(props)
    this.state = {
      loadingData: false,
    }
  }

  async componentDidMount() {
    this._isMounted = true;
    const { username } = this.state
    this.setState({ loadingData: true })

    try {
      await this.props.getUserData(username)
      this.setState({ loadingData: false })
    } catch (err) {
      console.log(err)
      this.setState({ loadingData: false })
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    return this.props !== nextProps
  }

render() {
  return(
    <div>{this.state.loadingData ? "Loading..." : this.props.userData}</div>
  )
}

Updated code to show the how I set up loadingData state. Some reason, adding shouldComponentUpdate shows, Loading... on the screen instead of userData from Redux. I'm not sure why...

2

2 Answers

0
votes

This will always return false because this.props is a different object than nextProps between each render.

For the simplest example of this:

console.log({} === {}) // false

By default (if using React.PureComponent) React will perform a "shallow equality" check. It will check the equality of each prop (but will not do so recursively because of performance reasons). (see the source).

As a first attempt, have you tried using React.PureComponent in place of React.Component?

If that doesn't help, I would recommend sharing the entire code snippet. shouldComponentUpdate usually is considered a "code smell" and commonly means there's a problem with another part of the code. It should not be used as control flow, but only for performance optimization.

If you still must implement shouldComponentUpdate, take a look at the default shallowEqual helper for a bit of inspiration.

-1
votes

Maybe you should look through this.

var jangoFett = {
    occupation: "Bounty Hunter",
    genetics: "superb"
};

var bobaFett = {
    occupation: "Bounty Hunter",
    genetics: "superb"
};

var callMeJango = jangoFett;

// Outputs: false
console.log(bobaFett === jangoFett);

// Outputs: true
console.log(callMeJango === jangoFett);