Nick Nick - 13 days ago 4x
React JSX Question

reactjs : ShouldComponentUpdate for states

How can I use

for states?

I can check:

shouldComponentUpdate(nextProps, nextState) {
return this.state.value != nextState.value;

But it doesn't have any sense for states. Because if I change state(
this.setState({value: 'newValue'})
will be equal

For example,

handleClick() {
this.setState({value: 'newValue'});


The shouldComponentUpdate(nextProps, nextState) method works for both props and state. In your example, after the onClick event the following method is fired by React.

shouldComponentUpdate(nextProps, nextState) {
  return this.state.value != nextState.value;

The key here is that in the above method the value of this.state.value is equal to what it was before the setState() call. This is thanks to the fact that in React:

setState() does not immediately mutate this.state but creates a pending state transition.
React docs:

Have a look at this demo: (full code below)

React keeps on state the count of every click on the button and also saves the randomly picked value (true or false). However thanks to the shouldComponentUpdate method, the component is re-rendered only if the previous value is not equal to upcoming / new value. This is why the displayed click count sometimes skips rendering its current state. You can comment out the whole shouldComponentUpdate method to re-render on every click.

class App extends React.Component {
  constructor() {
    this.state = {
      value: true,
      countOfClicks: 0
    this.pickRandom = this.pickRandom.bind(this);

  pickRandom() {
      value: Math.random() > 0.5, // randomly picks true or false
      countOfClicks: this.state.countOfClicks + 1

  // comment out the below to re-render on every click
  shouldComponentUpdate(nextProps, nextState) {
    return this.state.value != nextState.value;

  render() {
    return (
        shouldComponentUpdate demo 
        <p>Count of clicks: <b>{this.state.countOfClicks}</b></p>
        <button onClick={this.pickRandom}>
          Click to randomly select: true or false

  <App />,