How to rerender component without state change| React forceUpdate method


In react application, State and props are used to hold the data to the component.

what happens if state/props of a component changed?

usually state changes its values using setState method with new state object.

WWhenever state changed, React framework  does the following sequence of steps

  • calls shouldComponentUpdate method
  • if shouldComponentUpdate contains conditional logic which returns false, that means render method is not called  if it returns true, render method is called
  • finally reload the components happens

This is an example for re render the component on button click as button click update the state

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { counter: 0 };

  }
  onClick = () => {
    //this.forceUpdate();
    this.setState({ counter: 1 })

  };

  render() {
    console.log('Render called');

    return (
      <div> {this.state.counter}

        <button onClick={this.onClick}>Click</button>

      </div>
    )
  }
}

export default App;

How can retender a component without state being changed?

It means, programmatically setState change is not called for re render a component,

forceUpdate approach is being to used in a component,Even though this approach is avoided as react architecture principal

what happens if forceUpdate is called in React component.

  • shouldComponentUpdate method is ignored
  • It calls re render the component whether shouldComponentUpdate return true/false      
import './App.css';
import { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { counter: 0 };

  }
  onClick = () => {
    this.forceUpdate();

  };

  render() {
    console.log('Render called');

    return (
      <div> {this.state.counter}

        <button onClick={this.onClick}>Click</button>

      </div>
    )
  }
}

export default App;

       Above, is an example of forceUpdate in react components.

 How to achieve the same thing with react hooks   ## How to  force a component to re-render with react hooks?

Similar Posts