How to update react state without re-rendering component?

Here’s an example of only re-rendering when a particular condition is fulfilled (e.g. finished fetching).

For example, here we only re-render if the value reaches 3.

import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends React.Component { 
  state = { 
    value: 0, 
  }

  add = () => {
    this.setState({ value: this.state.value + 1});
  } 

  shouldComponentUpdate(nextProps, nextState) { 
    if (nextState.value !== 3) { 
      return false;
    }
    return true;
  }

  render() { 
    return (
      <React.Fragment>
        <p>Value is: {this.state.value}</p>
        <button onClick={this.add}>add</button>
      </React.Fragment>
    )
  }
}

render(<App />, document.getElementById('root'));

Live example here.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)